使用python发送电子邮件 Posted on 2016-12-07 123456789101112131415161718192021222324252627282930313233343536373839#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2016/12/7 上午9:40# @Author : Dwk# @File : send_email.py# smtplib 负责邮件的发送# email负责邮件的内容import smtplibfrom email.mime.text import MIMEText# 邮件服务器配置mail_host = "smtp.gmail.com"mail_user = "XXX"mail_pass = "XXXXXX"sender = "XXXXXXX"# 可接受多个发送地址receivers = ["XXXXXX"]# 邮件内容# text/html是指以html网页形式发送的,而text/plain是以纯文本格式发送的message = MIMEText('content', 'plant', 'utf-8')# 邮件主题message['Subject'] = 'title'# 发送方message['From'] = sender# 接受方message['To'] = receivers[0]# 登录并发送try: smtpObj = smtplib.SMTP() smtpObj.connect(mail_host, 25) smtpObj = smtplib.SMTP_SSL(mail_host, 465) smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) smtpObj.quit() print('success')except smtplib.SMTPException as e: print('error', e) 下面这个例子是添加了附件的123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2016/12/7 上午9:40# @Author : Dwk# @File : send_email.py# smtplib 负责邮件的发送# email负责邮件的内容import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.mime.image import MIMEImage# 邮件服务器配置mail_host = "smtp.gmail.com"mail_user = "dwk715"mail_pass = "XXXXX"sender = "dwk715@gmail.com"# 可接受多个发送地址receivers = ["dwk715@hotmail.com"]# 邮件内容# text/html是指以html网页形式发送的,而text/plain是以纯文本格式发送的# 邮件主题message = MIMEMultipart()message['Subject'] = '测试'# 发送方message['From'] = sender# 接受方message['To'] = receivers[0]# 使用HTML的正文内容with open('content.html', 'r') as f: content = f.read()part1 = MIMEText(content, 'html', 'utf-8')# 添加附件with open('addone.txt', 'r') as add: content2 = add.read()part2 = MIMEText(content2, 'plain', 'utf-8')# 设置内容类型,为二进制流part2['Content-Type'] = 'application/octet-stream'# 设置附件,添加文件名part2['Content-Disposition'] = 'attachment;filename="addone.txt"'# 添加照片附件,注意此处是rb读取方式with open('01.jpg', 'rb') as f_image: image = MIMEImage(f_image.read())# 设置内容类型,为二进制流image['Content-Type'] = 'application/octet-stream'# 设置附件,添加文件名image['Content-Disposition'] = 'attachment;filename="01.jpg"'# 添加内容到邮件主体中message.attach(part1)message.attach(part2)message.attach(image)# 登录并发送try: smtpObj = smtplib.SMTP() smtpObj.connect(mail_host, 25) smtpObj = smtplib.SMTP_SSL(mail_host, 465) smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) smtpObj.quit() print('success')except smtplib.SMTPException as e: print('error', e)