首页 / 操作系统 / Linux / Python 发送email
以下程序均来自《Python.UNIX和Linux系统管理指南》 http://www.linuxidc.com/Linux/2013-06/86448.htmsendemail.py#!/usr/bin/env pythonimport smtplibmail_server = "smtp.163.com"mail_server_port = 25from_addr = "from_username@163.com"to_addr = "to_username@163.com"from_header = "From: %s
" % from_addrto_header = "To: %s
" % to_addrsubject_header = "Subject: nothing interesting"body = "This is a not very interesting email."email_message = "%s
%s
%s
%s" %(from_header, to_header, subject_header, body)s = smtplib.SMTP(mail_server, mail_server_port)s.set_debuglevel(1)s.starttls()s.login("username", "password")s.sendmail(from_addr, to_addr, email_message)s.quit()
下面的程序是发送带附件的邮件email_attachment.py#!/usr/bin/env pythonimport emailfrom email.MIMEText import MIMETextfrom email.MIMEMultipart import MIMEMultipartfrom email.MIMEBase import MIMEBasefrom email import encodersimport smtplibimport mimetypesmail_server = "smtp.163.com"mail_server_port = 25from_addr = "from_username@163.com"to_addr = "to_usrename@163.com"subject_header = "Subject: Sending PDF Attachment"attachment = "disk_report.pdf"body = """this message sends a PDF attachment created with Report Lab."""m = MIMEMultipart()m["To"] = to_addrm["From"] = from_addrm["Subject"] = subject_headerctype, encoding = mimetypes.guess_type(attachment)print ctype, encodingmaintype, subtype = ctype.split("/", 1)print maintype, subtypem.attach(MIMEText(body))fp = open(attachment, "rb")msg = MIMEBase(maintype, subtype)msg.set_payload(fp.read())fp.close()encoders.encode_base64(msg)msg.add_header("Content-Disposition", "attachment", filename=attachment)m.attach(msg)s = smtplib.SMTP(mail_server, mail_server_port)s.set_debuglevel(1)s.starttls()s.login("username", "password")s.sendmail(from_addr, to_addr, m.as_string())s.quit()
效果