Python 发送email

2014-11-24 03:17:13 · 作者: · 浏览: 3

sendemail.py


#!/usr/bin/env python


import smtplib


mail_server = 'smtp.163.com'


mail_server_port = 25


from_addr = 'from_username@163.com'


to_addr = 'to_username@163.com'


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 = "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_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()



效果