Python发送邮件

使用smtplib发送邮件


def send_email(to_addrs,title,html_text='',mail_text='',enclosure='',cc_addrs=[]):

       # 发送者,标题,html格式文本,文本,附件,抄送,如果附件地址有中文需要解码gbk

     if not to_addrs:

         to_addrs = cc_addrs

        cc_addrs = []

  mail_info = {

"from": '111111111@163.com',

"to": to_addrs,

"CC": cc_addrs,

"hostname": "smtp.163.com",

"username": '111111111@163.com',

"password": '123456',

"mail_subject":title,

"mail_text": mail_text,

"mail_encoding": "utf-8"

}

try:

smtp = SMTP_SSL(mail_info["hostname"])

except Exception as e:

logger.error(u'无法连接网络或者邮箱服务器崩溃\n%s'%e)

return

# smtp.set_debuglevel(1)

smtp.ehlo(mail_info["hostname"])

smtp.login(mail_info["username"], mail_info["password"])

msg = MIMEMultipart('alternative')

msg["Subject"] = Header(mail_info["mail_subject"], mail_info["mail_encoding"])

msg["from"] =  Header('邮件发送平台','utf-8')

msg["to"] = ','.join(mail_info["to"])

msg["CC"] = ','.join(mail_info["CC"])

if html_text:

part2 = MIMEText(html_text, 'html', mail_info["mail_encoding"])

msg.attach(part2)

if mail_text:

part1 = MIMEText(mail_text, "plain", mail_info["mail_encoding"])

msg.attach(part1)

if enclosure:

part3 = MIMEApplication(open(enclosure,'rb').read())

part3.add_header('Content-Disposition', 'attachment', filename=os.path.split(enclosure)[1])

msg.attach(part3)

smtp.sendmail(mail_info["from"], mail_info["to"], msg.as_string())

smtp.quit()

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 公司内网有个论坛,各种公司的前沿消息都会有人在讨论。一忙起来,经常忘记逛论坛,所以写了个爬虫,爬取论坛前10...
    aialin阅读 4,447评论 0 11
  • python发送邮件 准备 python中发送邮件主要用的是smtplib和email两个模块,下面主要对这两个模...
    爱撒谎的男孩阅读 3,395评论 0 2
  • 在我们的工作中,会有诸如这种需求: Q1:我的测试用例实现自动构建了,怎么在构建完让程序通知我结果? Q2:我的监...
    唐T唐X阅读 3,449评论 3 0
  • 简单邮件传输协议(SMTP)是一种协议,用于在邮件服务器之间发送电子邮件和路由电子邮件。 Python提供smtp...
    易百教程阅读 44,305评论 4 62
  • 记得有一年的八月份,公司邀请来一位旅行摄影师给我们讲述他的旅行经历,和他所认为的理想的旅行方式。他说,他曾受到众多...
    NicKong阅读 2,675评论 2 1