以下程序均来自《Python.UNIX和Linux系统管理指南》

sendemail.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\r\n' % from_addrto_header = 'To: %s\r\n\r\n' % to_addrsubject_header = 'Subject: nothing interesting'body = 'This is a not very interesting email.'email_message = '%s\n%s\n%s\n\n%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_p_w_upload.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'p_w_upload = 'disk_report.pdf'body = '''this message sends a PDF p_w_upload created with Report Lab.'''m = MIMEMultipart()m['To'] = to_addrm['From'] = from_addrm['Subject'] = subject_headerctype, encoding = mimetypes.guess_type(p_w_upload)print ctype, encodingmaintype, subtype = ctype.split('/', 1)print maintype, subtypem.attach(MIMEText(body))fp = open(p_w_upload, 'rb')msg = MIMEBase(maintype, subtype)msg.set_payload(fp.read())fp.close()encoders.encode_base64(msg)msg.add_header("Content-Disposition", "p_w_upload", filename=p_w_upload)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()

效果