Send Email in Python

Send Email in Python

This article is a follow-up to my earlier article on how to send email from your Gmail account in Python. If have not read it, you can read it here: https://sapnaedu.com/how-to-send-email-from-your-gmail-account/. This is part of a series of article which I intend to cover on automating boring stuff.

Just to give a background, you come across a number of situation, where you need to send email from your application. For instance, you need to share a daily report to your client. Instead of sending the email manually, we can automate the entire process by sending the email automatically from your outlook account.

Step 1:  Python code to send Email from your Outlook account

We will be using smtplib module to send email via SMTP (Simple Mail Transfer Protocol). You can use the following code to login to your Outlook account.

server = smtplib.SMTP(smtp.outlook.com, 587)

context = ssl.create_default_context()

server.starttls(context=context) # Secure the connection

server.login(self.username, self.password)   # Use your Outlook username and password here

Step 2: Prepare the Email message

Here, we are using MIME module to prepare the email message. We can send the email as a plain text or HTML. In this tutorial, let us consider sending a very simple email having HTML text.

msg = MIMEMultipart()
msg['From']     = self.username
msg['To']       = recipient_email_address  # Single Email address
msg['Subject']  = "Test Email"

msg.attach(MIMEText(email_message, 'html'))

I am assuming that, the recipient email address is a single email account. We can also send email to multiple recipients in which case, each email address needs to be separated by “,”.

For instance, if you need to send email to test1@email.com, test2@email.com, test3@email.com msg object would look like:

msg['To'] = "test1@email.com, test2@email.com, test3@email.com"  # Multiple  Email address

Step 3: The final step is to send the email

server.sendmail(self.username, recipient_email_address, msg.as_string())

The complete code to send the email from your Outlook account can be downloaded from my GitHub account here: https://github.com/kirancshet/SendEmail-Outlook

As an exercise, can you explore the following:

  1. Send Email to multiple recipients
  2. Add CC to your email
  3. Add BCC to your email
  4. Attach a simple document with the email

I hope you find this article helpful.

 506 total views,  4 views today

Leave a Reply

Your email address will not be published. Required fields are marked *