Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Send mail with attachment in python
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os
import time
import random
def generate_message_id(msg_from):
domain = msg_from.split("@")[1]
r = "%s.%s" % (time.time(), random.randint(0, 100))
mid = "<%s@%s>" % (r, domain)
return mid
def send_mail(msg_from, to, subject, text,
files=[],server="localhost", debug=False):
assert type(to)==list
assert type(files)==list
msg = MIMEMultipart()
msg['From'] = msg_from
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
text = text.encode("utf-8")
text = MIMEText(text, 'plain', "utf-8")
msg.attach(text)
msg.add_header('Message-ID', generate_message_id(msg_from))
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="%s"'
% os.path.basename(file))
msg.attach(part)
if not debug:
smtp = smtplib.SMTP(server)
smtp.sendmail(msg_from, to, msg.as_string())
smtp.close()
return msg
#sendMail(["destination@dest.kio"], "hello","cheers", ["photo.jpg","memo.sxw"])
@sarancruzer
Copy link

sarancruzer commented Feb 28, 2018

I got this error , when i running this code
i am using Python3 can u help me pls

ImportError: No module named 'email.MIMEMultipart'

Loading

@Chanpreet-Singh
Copy link

Chanpreet-Singh commented Aug 16, 2018

For python3.x

You should update the imports as

from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
screenshot from 2018-08-16 16-13-37

Loading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment