import smtplib
import os
from email.mime.message import MIMEMessage
from email.MIMEBase import MIMEBase
from email import Encoders
from email.Utils import formatdate
from email.mime.multipart import MIMEMultipart
from email.MIMEText import MIMEText
def attachPdf(attachment, attachmentName, msg):
"""attaches a file <attachment> to the message <msg>. Name the file <attachmentName> in the mail"""
part = MIMEBase('application', "pdf") fp = open(attachment,"rb")
part.set_payload(fp.read())
fp.close()
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % attachmentName)
msg.attach(part)
def serverLogin(serverName, user, password, useTls=True):
"""logs into <server> with <user> and <password>
returns the smtp handle"""
smtp = smtplib.SMTP(serverName) if(useTls):
smtp.ehlo()
smtp.starttls()
smtp.ehlo
smtp.login(user, password)
return smtp
def buildMessage(sender, receiver, subject, body):
"""Builds a email messafe from the arguments."""
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender
msg['Date'] = formatdate(localtime=True)
msg['To'] = receiver
msg.attach(MIMEText(body, 'plain'))
return msg
if __name__ == "__main__":
myAddress = "Andre J. Aberer <mail@provider.de>"
toAddress = "Andre J. Aberer <mail@provider.de>"
attachment = "/path/to/attachment.pdf"
attachmentName = "invitation.pdf"
serverName = "mail.server.de"
user = "aberer"
password = "iLoveKitties"
subject = "Test"
body = "\nHello world!\n"
smtp = serverLogin(serverName, user, password)
msg = buildMessage(myAddress, toAddress, subject, body)
attachPdf(attachment, attachmentName, msg)
smtp.sendmail(myAddress, toAddress, msg.as_string())
smtp.quit()