Python @ DjangoSpin

Python: Sending a mail with smtplib & email modules

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Sending mail in Python

Sending mail in Python

Today, I was working on a script which involved sending a mail with an attachment. I used the following code, which uses the builtin smtplib & email modules. For sending emails with only text and no attachments at all, refer to the last piece of code, here.

Multiple Attachments

#####################################################################
# 		Script to send an email with multiple attachments  			#
#       			Script by: Lakshay Arora                  		#
#           		 Dated: January 1, 2016                         #
#####################################################################

# This script uses a gmail account to send the mail. If you
# have your account with another email provider, you will have
# to change the smtp_variable and smtp_port variable accordingly.

import smtplib, os
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders

# fill in the variables
smtp_server = "smtp.gmail.com"
smtp_port = 587	                                # for smtp.gmail.com
from_address = "from_address_here"              # e.g. username@gmail.com
from_password = "from_address_password_here"    # required by script to login using your username
to_address = "to_address_here"                  # e.g. username2@gmail.com
subject = "Subject_here"				
mail_body = "Body content here"
attachment_1 = r"absolute_path_of_file_1"       # e.g. file = r"C:\Folder1\text1.txt" # if you attach more than two files here, be sure to append them to the files dictionary below, as done for attachemnt_1 and attachment_2.
attachment_2 = r"absolute_path_of_file_2"

msg = MIMEMultipart()
msg['Subject'] =  subject
msg['To'] = to_address
msg.attach(MIMEText(mail_body))

files = []
files.append(attachment_1)
files.append(attachment_2)
for file in files:
    part = MIMEBase('application', "octet-stream")
    part.set_payload(open(file, "rb").read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(file)))
    msg.attach(part)

server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(from_address, from_password)
server.sendmail(from_address, to_address, msg.as_string())
server.quit()
##

Single Attachment

#####################################################################
# 		Script to send an email with single attachment  			#
#       			Script by: Lakshay Arora                  		#
#           		 Dated: January 2, 2016                         #
#####################################################################

# This script uses a gmail account to send the mail. If you
# have your account with another email provider, you will have
# to change the smtp_variable and smtp_port variable accordingly.

import smtplib, os
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders

# fill in the variables
smtp_server = "smtp.gmail.com"
smtp_port = 587									# for smtp.gmail.com
from_address = "from_address_here"				# e.g. username@gmail.com
from_password = "from_address_password_here"    # required by script to login using your username
to_address = "to_address_here"					# e.g. username2@gmail.com
subject = "Subject_here"				
mail_body = "Body content here"

msg = MIMEMultipart()
msg['Subject'] =  subject
msg['To'] = to_address
msg.attach(MIMEText(mail_body))

file = r"absolute_path_of_file_1"    # e.g. file = r"C:\Folder1\text1.txt"
part = MIMEBase('application', "octet-stream")
part.set_payload(open(file, "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(file)))
msg.attach(part)

server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(from_address, from_password)
server.sendmail(from_address, to_address, msg.as_string())
server.quit()
##

Text Only. No Attachment.

#####################################################################
# 		Script to send an email with no attachment  			    #
#       			Script by: Lakshay Arora                  		#
#           		 Dated: January 2, 2016                         #
#####################################################################

# This script uses a gmail account to send the mail. If you
# have your account with another email provider, you will have
# to change the smtp_variable and smtp_port variable accordingly.

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# fill in the variables
smtp_server = "smtp.gmail.com"
smtp_port = 587									# for smtp.gmail.com
from_address = "from_address_here"				# e.g. username@gmail.com
from_password = "from_address_password_here"    # required by script to login using your username
to_address = "to_address_here"					# e.g. username2@gmail.com
subject = "Subject_here"				
mail_body = "Body content here"

msg = MIMEMultipart()
msg['Subject'] =  subject
msg['To'] = to_address
msg.attach(MIMEText(mail_body))

server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(from_address, from_password)
server.sendmail(from_address, to_address, msg.as_string())
server.quit()
##

NOTE: If you get SMTPDataError when you execute the script, it might be because the file you are trying to attach is an executabe(.exe) or a batch file(.bat) or any other file type that google or your smtp provider does not allow. For gmail, refer to https://support.google.com/mail/answer/6590 for blocked file types. A possible turnaround for this is to rename the file on the sender side and then rename it on the destination side. That is, if you want to send a .bat file through mail, say one.bat, then rename the file to something like one.txt and send it over mail. Rename it again to one.bat on the destination. This should serve the purpose.

ANOTHER NOTE: If you get a failure message on the interpreter and a mail from your email provider saying that it blocked an attempt to login from a third-party app, you might have to turn on access for less secure apps in the settings of your email account. Doing so makes your email account vulnerable to hackers, so turn this access off once you no longer need it.

Read more about e-mails and Python on the official Python documentation.


See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply