Using Python3 To Send Email

Writing e-mails using Python3 can be a powerful tool for automating communication and streamlining processes. You can create and send emails directly from your Python script with just a few lines of code. This is the right place if you wish to utilise Python3 to send emails. You likely want your code to send you email reminders to users when they register accounts or to customers to remind them to pay dues. Manual e-mail sending is time-consuming and prone to mistakes, but Python3 simplifies it.

Using Python3 To Send Email

The Simple Mail Transfer Protocol may be used to send e-mails using Python’s built-in smtplib module (SMTP). In the case of the SMTP, RFC 821 protocol is being used by smtplib. The Gmail SMTP server is most likely to be used to send emails, but the same concepts also apply to other messaging services. You may quickly Google your email provider to validate its connection ports, even though most email providers use the same ones described here.

What to do

Create a Gmail account specifically for testing purposes, or set up an SMTP debugging server to publish emails you send to the command prompt instead of discarding them. Before sending any emails, check that your e-mail functionalities are bug-free and address any issues with functioning using a local SMTP debugging server.

Local SMTP Server Setup

Running a local SMTP debugging server with the help of a Python-preinstalled smtpd module will allow you to test email functionality. It discards emails instead of forwarding them to the provided address and publishes their contents to the console. Running a local debugging server eliminates the need to manage message encryption or use login credentials to access an e-mail server.

By entering the following commands in Command Prompt, you may launch a local SMTP debugging server:

$ python -m smtpd -c DebuggingServer -n localhost:1025

Use the same command on Linux, but with sudo before it.

Any emails sent over this service will be deleted and shown as a byte object for each line in the terminal window:

 
---------- MESSAGE FOLLOWS ----------
b'X-Peer: ::1'
b''
b'From: [email protected]'
b'To: [email protected]'
b'Subject: a test mail'
b''
b'Hey python learners
------------ END MESSAGE ------------

To build a single SMTP object, which can then be used to send an email, use the straightforward syntax shown here:

import smtplib

smtp__Obj = smtplib.SMTP( [host [, port [, local_hostname]]] )

The parameters are described in full below.

1. Host −This parameter is optional. This is the host where your SMTP server is located. In addition, the host’s IP address or domain name can be specified.

2. Port −You must give a port where the SMTP server listens if you give a host parameter. Normally, port 25 would be used.

3. Local hostname −If your SMTP server is operating on a local computer, you may use the localhost option. Sendmail is an instance method of an SMTP object that is commonly used to carry out the task of sending a message. It requires three variables.

4. Sender – A string containing the sender’s address.

5. Receivers −A list of strings representing the receivers, one for each recipient.

6. Message– The message is represented as a string prepared following the different RFCs.

For Example

Here is a straightforward Python 3 script for sending one email.

#!/usr/bin/python3

import smtplib

sender = 'from@__domain__.com'
receivers = ['to@__domain__.com']

message = """From: From Person <from@__domain__.com>
To: To Person <to@__domain__.com>
Subject: email to test SMTP 

Hey there test msg alert.
"""

try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, receivers, message)         
   print " email Successfully sent"
except SMTPException:
   print "Error: email not sent"

You have appropriately formatted the headers and used a triple quote to include a straightforward e-mail within this message. A blank line between the From, To, and Subject headers from the email’s content is required.

When you connect to the local machine’s SMTP server, use smtpObj to send emails. Then pass the message, the from address, and the destination address as inputs to the Sendmail method.

Also, you can use the smtplib client to connect to a remote SMTP server if your local workstation does not already run an SMTP server. If you aren’t using a webmail service, like Gmail or Yahoo Mail, your email provider should have given you the information for the outgoing mail server that you may provide them, which is as follows:

mail = smtplib.SMTP('smtp.techvidvan.com', 587)

Use of HTML content

HTML is especially helpful for formatting the text in your email (bold, italics, etc.) or if you want to include any photos, hyperlinks, or responsive material. The MIME (Multipurpose Internet Mail Extensions) Multipart email, combining HTML and plain text, is now the most popular e-mail. By using Python’s email.mime package, MIME messages are processed.

The MIMEText() objects in the example below will hold both the HTML version and the plain-text versions of our message, and the MIMEMultipart(“alternative”) instance combines them into one message with two different rendering options:

# Standard libraries to import
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

sender_email__ = "[email protected]"
receiver_email__ = "[email protected]"
password = input("Press enter after entering your password:")

message = MIMEMultipart("alternative")
message["Subject"] = "multipart test"
message["From"] = sender_email__
message["To"] = receiver_email__

text = """\
SAMPLE
"""
html = """\
<html>
  <body>
    <p>
       SAMPLE
    </p>
  </body>
</html>
"""

# Turn these into plain/html MIMEText objects
1stpart = MIMEText(text, "plain")
2ndpart = MIMEText(html, "html")

# Modify MIMEMultipart message to include HTML/plain-text 
# The email program will attempt to present the most recent portion first.
message.attach(1stpart)
message.attach(2ndpart)

# To create a secure connection to the server and send mail
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.techvidvan.com", 465, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(
        sender_email__, receiver_email__, message.as_string()
    )

The MIMEText() objects in the example below will hold both the HTML version and the plain-text versions of our message, and the MIMEMultipart(“alternative”) instance combines them into one message with two different rendering options:

This example defines the plain-text and HTML messages as string literals before being saved as plain/HTML MIMEText objects. These may then be included in the MIMEMultipart(“alternative”) message in the following sequence and transmitted using your secure email server connection. Remember that email clients will attempt to render the last portion first, so include the HTML message after the plain-text alternative.

Sending attachments as emails in Python

Sending attachments as e-mails using Python is a common operation, and it’s quite simple. Here’s an example of how you could go about doing it:

# Import the necessary modules
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import encoders

# Set up the server and login credentials
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('YOUR_EMAIL_ADDRESS', 'YOUR_EMAIL_PASSWORD')

# Create the email message
msg = MIMEMultipart()
msg['From'] = 'YOUR_EMAIL_ADDRESS'
msg['To'] = COMMASPACE.join(['RECIPIENT_1_EMAIL_ADDRESS', 'RECIPIENT_2_EMAIL_ADDRESS'])
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = 'Email with Attachment'

# Add the message body
msg.attach(MIMEText('This is the email body.'))

# Open the attachment file in binary mode
with open('ATTACHMENT_FILE', 'rb') as attachment:
    # Create a MIMEBase object with the attachment
    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)

    # Add header with the attachment file name
    part.add_header('Content-Disposition', "attachment; filename= %s" % 'ATTACHMENT_FILE')

    # Attach the binary data to the email
    msg.attach(part)

# Send the email
server.sendmail('YOUR_EMAIL_ADDRESS', ['RECIPIENT_1_EMAIL_ADDRESS', 'RECIPIENT_2_EMAIL_ADDRESS'], msg.as_string())

# Close the server connection
server.quit()

In this example, we’re using the smtplib module to connect to an SMTP server and send the email, and the email module to create the e-mail message and attach the file. The MIMEMultipart class is used to create a message that can contain multiple parts, such as text and attachments. The MIMEBase class creates the attachment itself, and the encoders module encodes the binary attachment data into a format that can be sent over email.

Add sending multiple personalised emails using python3

To send multiple personalised emails using Python, you can use a for loop to iterate over a list of recipient email addresses and create a separate email message for each recipient. Here’s an example:

# Import the necessary modules
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import encoders

# Set up the server and login credentials
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('YOUR_EMAIL_ADDRESS', 'YOUR_EMAIL_PASSWORD')

# List the recipients' email addresses.
recipients = ['RECIPIENT_1_EMAIL_ADDRESS', 'RECIPIENT_2_EMAIL_ADDRESS', 'RECIPIENT_3_EMAIL_ADDRESS']

# Iterate over the list of recipients
for recipient in recipients:
    # Create the email message
    msg = MIMEMultipart()
    msg['From'] = 'YOUR_EMAIL_ADDRESS'
    msg['To'] = recipient
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = 'Personalised Email'

    # Add the personalised message body
    msg.attach(MIMEText('Hello, %s! This is a personalised email.' % recipient))

    # Send the email
    server.sendmail('YOUR_EMAIL_ADDRESS', recipient, msg.as_string())

# Close the server connection
server.quit()

In this example, we create a list of recipient email addresses and then use a for loop to iterate over that list. Next, we create a new email message for each recipient and add the recipient’s email address to the To field. We also add a personalised message body using the MIMEText class and the %s string formatting operator, which allows us to insert the recipient’s email address into the message. Finally, we use the sendmail() method to send the email to the recipient.

Send email Using a transactional email service using python3

To send an email using a transactional email service with Python, you can use the smtplib module to connect to the service’s SMTP server and send the email. Of course, the specific steps for sending an email using a transactional email service will depend on the service you’re using, but here is an example of how you could do it with the popular service SendGrid:

# Import the necessary modules
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Set up the server and login credentials
server = smtplib.SMTP('smtp.sendgrid.net', 587)
server.starttls()
server.login('YOUR_SENDGRID_USERNAME', 'YOUR_SENDGRID_PASSWORD')

# Create the email message
msg = MIMEMultipart()
msg['From'] = 'YOUR_EMAIL_ADDRESS'
msg['To'] = 'RECIPIENT_EMAIL_ADDRESS'
msg['Subject'] = 'Email sent using SendGrid'

# Add the message body
msg.attach(MIMEText('This is the email body.'))

# Send the email
server.sendmail('YOUR_EMAIL_ADDRESS', 'RECIPIENT_EMAIL_ADDRESS', msg.as_string())

# Close the server connection
server.quit()

In this example, we use the smtplib module to connect to SendGrid’s SMTP server (smtp.sendgrid.net) and authenticate using our SendGrid username and password. We then create the e-mail message using the MIMEMultipart class, add the message body using the MIMEText class, and send the email using the sendmail() method.

Send email using a multichannel notification service using python3

To send an email using a multichannel notification service with Python, you can use the smtplib module to connect to the SMTP server and send the email. Of course, the specific steps for sending an email using a multichannel notification service will depend on the service you’re using, but here is an example of how you could do it with the popular service Twilio:

# Import the necessary modules
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Set up the server and login credentials
server = smtplib.SMTP('smtp.twilio.com', 587)
server.starttls()
server.login('YOUR_TWILIO_ACCOUNT_SID', 'YOUR_TWILIO_AUTH_TOKEN')

# Create the email message
msg = MIMEMultipart()
msg['From'] = 'YOUR_EMAIL_ADDRESS'
msg['To'] = 'RECIPIENT_EMAIL_ADDRESS'
msg['Subject'] = 'Email sent using Twilio'

# Add the message body
msg.attach(MIMEText('This is the email body.'))

# Send the email
server.sendmail('YOUR_EMAIL_ADDRESS', 'RECIPIENT_EMAIL_ADDRESS', msg.as_string())

# Close the server connection
server.quit()

In this example, we use the smtplib module to connect to Twilio’s SMTP server (smtp.twilio.com) and authenticate using our Twilio Account SID and Auth Token. We then create the e-mail message using the MIMEMultipart class, add the message body using the MIMEText class, and send the email using the sendmail() method.

Conclusion

In conclusion, writing an email using Python3 is a simple and efficient way to automate sending emails. Using the smtplib library, a user can easily create a script to send emails from a specified email address to a recipient with a customizable subject and message body. This can be useful for automated notifications, reminders, and other tasks that require sending emails. Additionally, using Python allows for greater flexibility and customization in the email-sending process. You can also receive emails using Python 3. This can be useful for automating tasks based on incoming emails, such as processing.

TechVidvan Team

The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today’s tech industry.