设为首页 加入收藏

TOP

Python 发送email
2014-11-24 03:17:13 来源: 作者: 【 】 浏览:2
Tags:Python 发送 email

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()



效果



】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Python 用socket模块实现检测端口.. 下一篇Python 生成pdf文件

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·请问微信4.0版本xwec (2025-12-24 22:48:42)
·电脑NVIDIA的文件夹 (2025-12-24 22:48:40)
·如何看待微信新版本 (2025-12-24 22:48:37)
·C语言中如何将结构体 (2025-12-24 22:20:09)
·纯C语言结构体成员变 (2025-12-24 22:20:06)