1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| import smtplib import os.path from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication
port = 25 smtp_server = 'xxx'
def mail(sender, receiver, subject, content, files=None): """ sender, receiver: a string of comma separated email addresses content: html or plain text files: a list of pathnames of attachments """ message = MIMEMultipart('alternative') message['Subject'] = subject message['From'] = sender message['To'] = receiver
disclaimer = 'The HTML version of this email may not be rendered properly, displaying plain text instead.\n\n' html = content content = disclaimer + content plain_part = MIMEText(content, 'plain') html_part = MIMEText(html, 'html') message.attach(plain_part) message.attach(html_part)
if files: for filename in files: with open(filename, 'rb') as attachment: binary_part = MIMEApplication(attachment.read())
binary_part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(filename)) message.attach(binary_part)
with smtplib.SMTP(smtp_server, port) as server: recipients = [to_addr.strip() for to_addr in receiver.split(',')] server.sendmail(sender, recipients, message.as_string())
if __name__ == '__main__': sender = '' receiver = '' subject = '[TEST] multipart test 中文測試' content = '<h1>Hello, World</h1>' files = ['中文繁體UTF8.txt', '中文简体GB2312.txt'] mail(sender, receiver, subject, content, files)
|