python 发送email

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

sendemail.py
#!/usr/bin/env python
import smtplib
mail_server = 'smtp.163.com'
mail_server_port = 25
from_addr = '[email protected]'
to_addr = '[email protected]'
from_header = 'From: %s\r\n' % from_addr
to_header = 'To: %s\r\n\r\n' % to_addr
subject_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_attachment.py
#!/usr/bin/env python
import email
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import encoders
import smtplib
import mimetypes
mail_server = 'smtp.163.com'
mail_server_port = 25
from_addr = "[email protected]"
to_addr = "[email protected]"
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_addr
m['From'] = from_addr
m['Subject'] = subject_header
ctype, encoding = mimetypes.guess_type(attachment)
print ctype, encoding
maintype, subtype = ctype.split('/', 1)
print maintype, subtype
m.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()

效果

你可能感兴趣的:(python,email)