Last modified: Jan 10, 2023 By Alexander Williams
How to send an email with attachment in python
Probably you are here now because you want to know how to send a mail with attachment or many attachments. So we will do that in the best way.
sending a mail with attachment
If you would use the Gmail server you must enable POP download and IMAP access in your account settings, you also must enable less secure app access in your settings.
syntax:
import os
import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email.mime.base import MIMEBase
from email import encoders
server = smtplib.SMTP()
server.connect('smtp.gmail.com','587')
server.ehlo()
server.starttls()
server.login("ex@gmail.com", "password") #log in to the server
email_from = 'ex0@gmail.com' # email_sender
email_to = 'exx@gmail.com' # email_receiver
Subject = 'helloworld' # subject
attachment = '/home/py/Desktop/pytutorial-project/file.txt' #attachment
content = '<h1>Hello world</h1>' #content
msg = MIMEMultipart()
msg['From'] = email_from
msg['To'] = email_to
msg['Subject'] = Subject
with open(attachment, 'rb') as attachments:
file_name = os.path.basename(attachment) #getting basename file
part = MIMEBase('application','octet-stream') # Content-Type
part.set_payload(attachments.read()) # seting the payload
part.add_header('Content-Disposition', "attachment; filename= %s" % file_name)
encoders.encode_base64(part)
msg.attach(part) #attaching the file
server.sendmail(email_from, email_to, msg.as_string()) # sending the email
# sucess message
print('the mail has been sent')
sending a mail with a many attachments
if would like send an email with many attachments you can do this
syntax:
server = smtplib.SMTP()
server.connect('smtp.gmail.com','587')
server.ehlo()
server.starttls()
server.login("ex@gmail.com", "password") #log in to the server
email_from = 'ex0@gmail.com'
email_to = 'exx@gmail.com'
Subject = 'helloworld'
attachment = ['/home/py/Desktop/pytutorial-project/file.txt', '/home/py/Desktop/pytutorial-project/file2.txt', '/home/py/Desktop/pytutorial-project/file3.txt'] #list of attachments
content = '<h1>Hello world</h1>'
msg = MIMEMultipart()
msg['From'] = email_from
msg['To'] = email_to
msg['Subject'] = Subject
#send multi attachment
for x in attachment:
with open(x, 'rb') as attachments:
file_name = os.path.basename(x)
part = MIMEBase('application','octet-stream')
part.set_payload(attachments.read())
part.add_header('Content-Disposition', "attachment; filename= %s" % file_name)
encoders.encode_base64(part)
msg.attach(part) #attaching the file
msg.attach(MIMEText(content, 'html')) #attaching the message as html
server.sendmail(email_from, email_to, msg.as_string()) # sending the email
# sucess message
print('the mail has been sent')