python with gmail - How to send email attachments?

5 Answers

this is the code I ended up using:

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Encoders

SUBJECT = "Email Data"

msg = MIMEMultipart()
msg['Subject'] = SUBJECT 
msg['From'] = self.EMAIL_FROM
msg['To'] = ', '.join(self.EMAIL_TO)

part = MIMEBase('application', "octet-stream")
part.set_payload(open("text.txt", "rb").read())

part.add_header('Content-Disposition', 'attachment; filename="text.txt"')


server = smtplib.SMTP(self.EMAIL_SERVER)
server.sendmail(self.EMAIL_FROM, self.EMAIL_TO, msg.as_string())

Code is much the same as Oli's post. Thanks all

Code based from Binary file email attachment problem post.

csv pdf outlook

I am having problems understanding how to email an attachment using Python. I have successfully emailed simple messages with the smtplib. Could someone please explain how to send an attachment in an email. I know there are other posts online but as a Python beginner I find them hard to understand.

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import smtplib

msg = MIMEMultipart()

# to send
mailer = smtplib.SMTP()
mailer.sendmail(from_, to, msg.as_string())

Adapted from here.

Gmail version, working with Python 3.6 (note that you will need to change your Gmail settings to be able to send email via smtp from it:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from os.path import basename

def send_mail(send_from: str, subject: str, text: str, 
send_to: list, files= None):

    send_to= default_address if not send_to else send_to

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = ', '.join(send_to)  
    msg['Subject'] = subject


    for f in files or []:
        with open(f, "rb") as fil: 
            ext = f.split('.')[-1:]
            attachedfile = MIMEApplication(, _subtype = ext)
                'content-disposition', 'attachment', filename=basename(f) )

    smtp = smtplib.SMTP(host="", port= 587) 
    smtp.sendmail(send_from, send_to, msg.as_string())


username = ''
password = 'top-secret'
default_address = [''] 

send_mail(send_from= username,
send_to= None,
files= # pass a list with the full filepaths here...

To use with any other email provider, just change the smtp configurations.

Other answers are excellent, though I still wanted to share a different approach in case someone is looking for alternatives.

Main difference here is that using this approach you can use HTML/CSS to format your message, so you can get creative and give some styling to your email. Though you aren't enforced to use HTML, you can also still use only plain text.

Notice that this function accepts sending the email to multiple recipients and also allows to attach multiple files.

I've only tried this on Python 2, but I think it should work fine on 3 as well:

import os.path
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

def send_email(subject, message, from_email, to_email=[], attachment=[]):
    :param subject: email subject
    :param message: Body content of the email (string), can be HTML/CSS or plain text
    :param from_email: Email address from where the email is sent
    :param to_email: List of email recipients, example: ["", ""]
    :param attachment: List of attachments, exmaple: ["file1.txt", "file2.txt"]
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = ", ".join(to_email)
    msg.attach(MIMEText(message, 'html'))

    for f in attachment:
        with open(f, 'rb') as a_file:
            basename = os.path.basename(f)
            part = MIMEApplication(, Name=basename)

        part['Content-Disposition'] = 'attachment; filename="%s"' % basename

    email = smtplib.SMTP('')
    email.sendmail(from_email, to_email, msg.as_string())

I hope this helps! :-)

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

smtp_ssl_host = ''  #
smtp_ssl_port = 465
s = smtplib.SMTP_SSL(smtp_ssl_host, smtp_ssl_port)
s.login(email_user, email_pass)

msg = MIMEMultipart()
msg['Subject'] = 'I have a picture'
msg['From'] = email_user
msg['To'] = email_user

txt = MIMEText('I just bought a new camera.')

filename = 'introduction-to-algorithms-3rd-edition-sep-2010.pdf' #path to file
attach = email.mime.application.MIMEApplication(,_subtype="pdf")

For explanation, you can use this link it explains properly



python   email