Open-source News

Use Django to send emails with SMTP

opensource.com - Tue, 12/13/2022 - 16:00
Use Django to send emails with SMTP Sofiia Tarhonska Tue, 12/13/2022 - 03:00

Numerous professions utilize simple mail transfer protocol (SMTP) to deliver emails to their end users. SMTP also retrieves messages, though that has not been its primary use case. Open source frameworks like Django, a Python-based web framework, allows more control for sending emails using functions and expressions.

This article shows how to configure an SMTP server and send emails in Django using SMTP.

Project setup and overview

Before proceeding, this tutorial requires a code editor (such as VS Code or Codium) on your preferred device. 

Start by creating a new directory using the command in the terminal:

mkdir exampledirectory

Then change into the directory using the command:

cd exampledirectory

Within the newly created directory, create a virtual environment using the built-in venv module in the command terminal:

python -m venv

This command creates a virtual environment within the folder created earlier. To activate it, use the following command in the terminal:

On Linux and Mac:

source .virtenv/bin/activate

On Windows:

\Scripts\activateCreating a Django project

After activating the virtual environment, proceed to install the Django package from pip:

pip install django

Create a new Django project:

python -m django startproject NewEmailProject

This command creates a project with the name NewEmailProject. To run the project, head to the project directory (NewEmailProject) and run the server:

python manage.py runserver

Open the link for the developmental server in a browser. You see the Django homepage with release notes.

More great content Free online course: RHEL technical overview Learn advanced Linux commands Download cheat sheets Find an open source alternative Explore open source resources Configuration for sending emails

Next, open the settings.py file (in the NewEmailProject folder) to customize configurations for sending emails using Django.

Scroll to the end of the code and update the file with the following code:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.yourserver.com'
EMAIL_USE_TLS = False
EMAIL_PORT = 465
EMAIL_USE_SSL = True
EMAIL_HOST_USER = 'your@djangoapp.com'
EMAIL_HOST_PASSWORD = 'your password'

Change the value of the EMAIL_HOST depending on your email client. Here are the acceptable values for common email clients:

  • Gmail: smtp.gmail.com

  • Outlook: smtp-mail.outlook.com

  • Yahoo: smtp.mail.yahoo.com

You can change the EMAIL_PORT or leave 465 as the default.

You can use the secure socket layer (SSL) and transport socket layer (TSL) interchangeably as they specify connection security.

To figure out other custom configurations for your email server, check out the full Django Project documentation.

SMTP email backend

The EMAIL_BACKEND expression helps determine the most suitable backend when sending emails through the Django SMTP server. This variable points to smtp.EmailBackend, which receives all the parameters needed for sending emails. It tells Django to send the email to the recipient email using SMTP and not to the console.

Sending emails with SMTP

When the environment is set up and settings.py is updated, you can send emails in Django. You can use an HTML form that sends a post request of the necessary information needed for sending an email.

Create a Django application for sending emails:

python manage.py startapp mail

Next, open the settings.py file and add the Django application (mail) to the INSTALLED_APPS list:

INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"mail"]Send mail function

In the mail application's views.py file, start by importing the EmailMessage and get_connection from django.core.mail:

from django.core.mail import EmailMessage, get_connection

The EmailMessage class is responsible for creating the email message itself. The get_connection() function returns an instance of the email backend specified in EMAIL_BACKEND.

Now create a function that accepts a POST request, which contains form data submitted from the client side. Followed by the get_connection() functions parameters containing the email configurations created in the project settings.py file.

Next, import the settings:

from django.conf import settings

This import allows access to the email configurations created in the settings.py. Next, create the variables:

subject, recipient_list,

Then you can message, and store the corresponding attributes used in the HTML form. The email_from variable contains the sender email, which is obtained from EMAIL_HOST_USER in the settings.py file.

After the variables are processed, the EmailMessage class sends an email using the sends() method, and then closes the connection. The send_email() function renders the home.html file containing the email form.

You can create a templates folder within your mail application and store the HTML files within that folder:

from django.core.mail import EmailMessage, get_connection
from django.conf import settings

def send_email(request):  
   if request.method == "POST":
       with get_connection(  
           host=settings.EMAIL_HOST,
     port=settings.EMAIL_PORT,  
     username=settings.EMAIL_HOST_USER,
     password=settings.EMAIL_HOST_PASSWORD,
     use_tls=settings.EMAIL_USE_TLS  
       ) as connection:  
           subject = request.POST.get("subject")  
           email_from = settings.EMAIL_HOST_USER  
           recipient_list = [request.POST.get("email"), ]  
           message = request.POST.get("message")  
           EmailMessage(subject, message, email_from, recipient_list, connection=connection).send()  
 
   return render(request, 'home.html')

This is a bootstrap form for generating a message:

<form method="post" action=".">
 {% csrf_token %}
 <div class="mb-3">
     <label for="exampleFormControlInput1" class="form-label">Receipt email address</label>
     <input type="text" class="form-control" name="email" id="exampleFormControlInput1" placeholder="Receipt email address">
   </div>
   <div class="mb-3">
     <label for="exampleInputSubject" class="form-label">Subject</label>
     <input type="text" class="form-control" name="subject" id="exampleInputSubject">
   </div>
   <div class="mb-3">
     <label for="exampleFormControlTextarea1" class="form-label">Message</label>
     <textarea class="form-control" id="exampleFormControlTextarea1" name="message" rows="3"></textarea>
   </div>
   <button type="submit" class="btn btn-primary">Send</button>
 </form>

This form sends a post request to the send_email() function. This processes the form data and sends the email to the recipients.

Now open the urls.py file in the NewEmailProject folder to create the homepage URL. Update the urlpattern list by adding the code path("", send_email) .

Sending email to multiple recipients

To specify multiple recipients when sending the same email, create a new function called send_emails within the views.py file and modify the send function code:

                                     
def send_emails(request):  
    if request.method == "POST":
        with get_connection(  
              host=settings.EMAIL_HOST,
        port=settings.EMAIL_PORT,  
       username=settings.EMAIL_HOST_USER,  
       password=settings.EMAIL_HOST_PASSWORD,  
        use_tls=settings.EMAIL_USE_TLS
        ) as connection:  
            recipient_list = request.POST.get("email").split()  
            subject = request.POST.get("subject")  
            email_from = settings.EMAIL_HOST_USER  
            message = request.POST.get("message")  
            print(type(recipient_list))
            EmailMessage(subject, message, email_from, recipient_list, connection=connection).send()  
 
    return render(request, 'send_emails.html')

For the recipient_list variable, I'm using the Python split() method to convert the recipients email string to list so that I can email all of them.

Next, create another HTML file called send_emails.html in the templates folder and use the same form code for the home.html file within it.

To specify multiple email recipients, use a space between each email address:

first@gmail.com second@gmail.com third@gmail.com

You should also update the urlpattern list by adding the code:

path("send-emails/", send_email)Sending HTML emails

You can also send HTML emails with Django using a slightly modified version of the send_email function:

html_message = '''<h1>this is an automated message</h1>'''
msg = EmailMessage(subject, html_message, email_from,recipient_list, connection=connection)
msg.content_subtype = "html"
msg.send()Sending emails with attachment

To include attachment to mails, create a variable and put it in the file path in a string like this:

attachment = "mail/templates/example.png"

Then, move the EmailMessage function to a variable and call the attach_file method followed by the send method:

msg = EmailMessage(subject, message, email_from, recipient_list, connection=connection)
msg.attach_file(attachment)
msg.send()Django email libraries

This guide on sending emails in Django would not be complete if I didn't mention the email libraries that are available to users. Here are some noteworthy email libraries.

  • Django mailer is a Django app for queuing as it saves emails in a database and sends the mail out at a designated time.
  • Django templated email aims to send templated emails. It offers features like configurable template naming and location, template inheritance, and adding recipients to the CC and BCC lists.
  • Anymail allows the use of an email service provider (ESP). By using django.core.mail, it provides a sustained API that avoids tying your code to a single ESP.
Emailing with Django

Sending emails in Django can sound daunting, but it's as simple as creating a virtual environment. You can add Django to the environment and create an email backend. Finally, you can set up an HTML template. Give it a try.

Django is a Python-based web framework that allows more control for sending emails using functions and expressions.

Image by:

Ribkahn via Pixabay, CCO

Email Python What to read next This work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License. Register or Login to post a comment.

Drupal 10 is worth a fresh look

opensource.com - Tue, 12/13/2022 - 16:00
Drupal 10 is worth a fresh look Martin Anderso… Tue, 12/13/2022 - 03:00

The popular Drupal open source content management system (CMS) reaches a significant milestone when version 10 is released on December 14. Personally, I think Drupal X sounds way cooler, but so far, my calls to name it that haven't gotten much traction. I enlisted the help of my friend Aaron Judd of Northern Commerce to give us a sense of how cool Drupal X could look:

Image by:

Aaron Judd of Northern Commerce

What's a Drupal, anyway?

Drupal is an open source CMS and development framework. While other CMS options focus on simple long-form content (think blogs) or entirely free-form content (like in Wix or Squarespace), Drupal has made a name for itself in handling more complex content architectures, in multiple languages, with robust content governance. Drupal sites (like this site, Opensource.com!) benefit from a strong role-based access control (RBAC) system, unlimited custom roles and workflows, and a powerful and extensible media library.

Here's a rundown for anyone who hasn't kept tabs on what's coming in the newest major version.

A fresh face

Most Drupal sites use custom themes to give them a unique look and feel. Still, the initial experience you have when installing a CMS matters. In Drupal, themes define the look and feel of a site, and you can use different themes for public and administrative experiences. Until recently, the Bartik and Seven themes had been the default face of Drupal for more than a decade. To put that in context, when Bartik was released, the most popular browser in the world was Internet Explorer 8. A lot has changed since then, particularly around best practices for building websites.

In fact, a significant change in Drupal 10 will be the removal of support for Internet Explorer (IE), which is itself no longer supported by Microsoft and hasn't seen major updates since 2013. That may not sound like an improvement, but continued support for IE kept the community from adopting modern markup and styling. For example, thanks to being unencumbered by support for legacy browsers, Drupal 10 includes a new responsive grid layout that's so innovative it got a writeup in CSS Tricks.

Image by:

(Martin Anderson-Clutz, CC BY-SA 4.0)

The new faces of Drupal are two brand new themes: Olivero for visitors and Claro for admins. In addition to being fresh and modern designs, both were developed with accessibility as a top priority.

Improvements under the hood

More than a decade ago, the Drupal community decided to "Get Off the Drupal Island." That meant adopting solutions shared across popular projects and frameworks instead of ones developed and maintained exclusively by the Drupal community. Today Drupal leverages a variety of projects and libraries whose names will be familiar to open source developers who have never touched Drupal: Symfony, Composer, CKEditor, Twig, Nightwatch, and more.

That has brought a variety of powerful capabilities to Drupal and allowed it to contribute back to those solutions, benefitting a broader set of developers. It has also become a determining factor for the cadence of Drupal's major version releases.

To illustrate, consider that Drupal 7 was released in early 2011. Drupal 8 was released almost five years later, towards the end of 2015. Drupal 9 was released in June of 2020, with a key motivator being the move to supported versions of underlying dependencies and removing deprecated code. And now, roughly two and half years later, we're already planning to release Drupal 10. This new major version will leverage updated versions of PHP, Symfony, and Composer, among others.

An all-new editor

An upgrade of particular note is the move to CKEditor 5. Although notionally an incremental update, under the hood CKEditor 5 was completely rewritten, much the same as the transition from Drupal 7 to 8. In addition to a sleeker interface, CKEditor 5 has the potential for exciting new capabilities, such as real-time collaboration. Drupal's CKEditor integration for version 5 has already been augmented with a number of UI enhancements. For example, media placed within content can be configured using an overlaid toolbar ribbon instead of needing to launch a modal dialog to access these settings. Also, the styles dropdown now includes a preview of each type available.

Image by:

(Martin Anderson-Clutz, CC BY-SA 4.0)

More great content Free online course: RHEL technical overview Learn advanced Linux commands Download cheat sheets Find an open source alternative Explore open source resources A look ahead

Earlier in 2022, Drupal creator and project lead Dries Buytaert announced a focus on "ambitious site builders." This means that while the community will continue to work on making the developer experience better in general, moving forward there is a particular focus on making it easier to create engaging experiences in Drupal without having to write code or use command-line tools. Three strategic initiatives embody this new focus: Automatic Updates, the Project Browser, and Recipes.

Automatic Updates will reduce the total cost of ownership for Drupal sites and help them be more secure by ensuring they always have the latest core security patches. This will be a major benefit for site owners and Drupal development teams everywhere. However, judging by personal experience, Wednesday night pizza sales may take a hit (traditionally, the Drupal security team releases updates on the third Wednesday of the month). There is now a stable release of Automatic Updates as a contrib module. Work has begun to move this into Drupal core, so all Drupal sites will eventually be able to leverage this capability.

The Project Browser makes Drupal sites easier to build, maintain, and evolve by allowing site builders to search and browse through a subset of Drupal's vast catalog of available modules, prefiltered to the site's Drupal version, for security, stability, and more. A site builder can select, download, and install a module without leaving the site's web interface. In fact, there's an "app store" like interface meant to promote the most popular modules available that are compatible with the current site's version of Drupal. While other CMS options have had similar offerings, this advancement means you don't need to sacrifice ease-of-use to take advantage of the power of Drupal. Also, all of the thousands of modules listed are 100% free. 

For many years Drupal has had a concept of distributions. These are opinionated versions of Drupal designed to meet specific use cases such as media publishing, fundraising, intranet portals, and more. While distributions have proven an excellent way to accelerate initial development, in practice, they have been known to require significant work to maintain and create extra work for site owners during maintenance. The Recipes initiative aims to make more granular, composable functionality available when building a site. Want to add a staff directory, events calendar, or locations map to your site? In the future, this will be as easy as installing a recipe and then customizing it to meet your site's specific needs.

It's an exciting time to try Drupal

Drupal 10 is the culmination of work contributed by thousands of dedicated and talented community members worldwide. If you're not already using Drupal, we hope you'll try it out for your next project. There's a common saying among Drupalists: "Come for the code, stay for the community."

Drupal 10 is chockful of useful features, a fresh look, and a brand-new editor.

Image by:

Opensource.com

Drupal What to read next This work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License. Register or Login to post a comment.

Try this Linux web browser as your file manager

opensource.com - Tue, 12/13/2022 - 16:00
Try this Linux web browser as your file manager Seth Kenlon Tue, 12/13/2022 - 03:00

Konqueror is a file manager and web browser for the KDE Plasma Desktop. In many ways, Konqueror defined "network transparency," as it applied to a personal desktop. With Konqueror, you can browse remote network files (including the Internet itself, which really is just a collection of remote files viewed through a fancy lens) just as easily as browsing your local files. Sometimes there was some configuration and setup required, depending on what kind of file share you needed to access. But ultimately, the goal of having instant access to all the data you had permission to view was a reality with Konqueror in ways no other file manager had achieved. And at its peak, the open source web engine it developed (KHTML) was adopted by both Apple and Google, and lives on today as the core library of modern web browsing and, technically, Electron app development.

Today, the KDE Plasma Desktop lists Konqueror as a web browser. Officially, file management has shifted over to Dolphin, but Konqueror is still capable of doing the job. For the full and classic Konqueror experience, you should try the Plasma Desktop 3.x fork TDE, but in this article I use Konqueror in KDE Plasma Desktop version 5.

Install Konqueror

If you're running KDE Plasma Desktop already, you may already have Konqueror installed. If not, you can install it from your distribution's software repository. On Fedora, CentOS, Mageia, OpenMandriva, and similar:

$ sudo dnf install -y konqueror konqueror-plugins

On Debian, Linux Mint, Elementary, and similar:

$ sudo apt install -y konqueror konqueror-plugins Image by:

(Seth Kenlon, CC BY-SA 4.0)

Configure Konqueror as a file manager

The most convenient feature of Konqueror is that it's a web browser in addition to being a file manager. Or at least, that's theoretically its most convenient feature. If you're not using Konqueror as a web browser, then you may not want the URL field or the search engine field at the top of every file manager window.

As with most KDE applications, Konqueror is highly configurable. You can reposition and add and remove toolbars, add or remove buttons, and so on.

To adjust what toolbars are displayed, launch Konqueror and go to the Settings menu and select Toolbars Shown. The Main toolbar is probably all you really need for file management. It's the toolbar with navigation buttons on it. However, you may not even need that, as long as you're happy to navigate with keyboard shortcuts or using the Go menu.

Keyboard navigation in Konqueror is the same as in Dolphin:

  • Alt+Left arrow: Back one step

  • Alt+Up arrow: Move to parent directory

  • Alt+Home: Go to home directory

Side panel

To get a side panel with a listing of common folders, press F9 or select Show Sidebar from the Settings menu. This adds a button bar along the left side of the Konqueror window. Click the Home icon to display a file tree of your home directory.

Image by:

(Seth Kenlon, CC BY-SA 4.0)

As the button bar suggests, this side panel can serve many purposes. Instead of your home directory, you can display bookmarked locations, a history of recent locations you've visited, remote filesystems, and more.

Applications

Some people are used to an application menu. It's efficient and quick, and always in the same place. Other people prefer to launch applications from the terminal.

There's yet another way to view application launchers, though. Konqueror's Go menu allows you go to a meta location called Applications, which lists application launchers, by category, as files in a file manager.

Image by:

(Seth Kenlon, CC BY-SA 4.0)

You can see this in Dolphin, too, by manually typing applications: in the location field, but of the two it's Konqueror that provides a menu option to go there directly.

More Linux resources Linux commands cheat sheet Advanced Linux commands cheat sheet Free online course: RHEL technical overview Linux networking cheat sheet SELinux cheat sheet Linux common commands cheat sheet What are Linux containers? Our latest Linux articles Network folders

Similarly, Konqueror also provides a menu selection to go to network folders. The greatest network folder of them all is the Internet, but Network Folders is the meta location for network protocols other than HTTP. Most remote locations require some setup because they usually require authentication to access. Most of them can be configured through System Settings, including file systems accessible over Bluetooth, SMB or CIFS, MTP devices, Fish (file system over SSH), and even Google Drive.

Split view

You can split the Konqueror window into panes, allowing you to see two folders at once without opening two windows. There are two split options: a vertical split with one pane on the left and the other on the right, or a horizontal split with one pane above the other.

To split the Konqueror window, go to the Window menu and select either Split View Left/Right or Spit View Top/Bottom. Each pane is independent of the other, so you can navigate around in one pane, and then drag and drop files from one to the other.

Conquering your file system

Konqueror isn't just a file manager, and I don't think the developers of the Plasma Desktop expect you to use it as your primary file manager. There's even an option in the File menu to open a location in Dolphin, which indicates that Konqueror is a web browser with a file manager component. But that file manager component is a nice feature to have when you need it. And if you're not a fan of all the features Dolphin offers, Konqueror could be a suitable alternative.

The KDE Plasma Desktop lists Konqueror as a web browser, but it is also a functional Linux file manager.

Linux What to read next This work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License. Register or Login to post a comment.

How to Connect Remote Linux via SSH ProxyJump and ProxyCommand

Tecmint - Tue, 12/13/2022 - 13:56
The post How to Connect Remote Linux via SSH ProxyJump and ProxyCommand first appeared on Tecmint: Linux Howtos, Tutorials & Guides .

Brief: In this guide, we demonstrate how to use SSH ProxyJump and SSH ProxyCommand commands when connecting to a jump server. In our previous guide on how to set up an SSH Jump Server,

The post How to Connect Remote Linux via SSH ProxyJump and ProxyCommand first appeared on Tecmint: Linux Howtos, Tutorials & Guides.

Btrfs With Linux 6.2 Bringing Performance Improvements, Better RAID 5/6 Reliability

Phoronix - Tue, 12/13/2022 - 05:50
The Btrfs and EXT4 file-system updates for the Linux 6.2 merge window have been submitted. The Btrfs changes are rather notable with continued performance enhancements as well as making some reliability improvements to its native RAID5/RAID6 modes...

IOMMUFD Submitted For Linux 6.2 To Overhaul IOMMU Handling

Phoronix - Tue, 12/13/2022 - 04:20
After being in various forms of discussion since 2017, IOMMUFD has been submitted for the Linux 6.2 kernel as it lays the groundwork for aiming to overhaul IOMMU handling by QEMU and virtual machines on Linux...

Pages