To send an email along with attachment using SMTP

Sanket Doshi
1 min readOct 21, 2018

--

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

smtplib allows using simple mail transfer protocol used to send emails.

MIME Multi-Purpose Internet Mail Extensions is used to transfer different types of messages along with attachments. Using this the browsers know what type of file is present in an email.

smtp_ssl_host = 'smtp.gmail.com'  # smtp.mail.yahoo.com
smtp_ssl_port = 465
s = smtplib.SMTP_SSL(smtp_ssl_host, smtp_ssl_port)
s.login(email_user, email_pass)

Here, we connect with SMTP server using SSL. After connecting we log in to our mail so that we can send mail from this email address. email_user is your’s email id and email_pass is the password of your email id.

msg = MIMEMultipart()
msg['Subject'] = 'I have a file to send'
msg['From'] = sender #email_user
msg['To'] = receiver's email id

MIMEMultipart() means it consists of multiple messages and each of them defines its own Content-Type, for example, it contains pdf along with HTML or some text.

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

MIMEText represents that only text message is present in the mail so no tree structure is present. attach() is used to add some part to the message which will be sent in an email.

filename = 'path to your file'
fo=open(filename,'rb')
file = email.mime.application.MIMEApplication(fo.read(),_subtype="extension of file")
fo.close()
attach.add_header('Content-Disposition','attachment',filename=filename)
msg.attach(file)

Content-Disposition means that data to be shown as an attachment and should be allowed to download it.

s.send_message(msg)
s.quit()

send_message() is used to send the message .

quit() closes the connection to the server.

--

--

Sanket Doshi

Currently working as a Backend Developer. Exploring how to make machines smarter than me.