python 发送邮件的两种方式【终极篇】
一,利用python自带的库 smtplib简单高效
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.header import Header import smtplib from django.conf import settingsmail_host = settings.EMAIL_HOSTmail_user = settings.EMAIL_HOST_USERmail_pass = settings.EMAIL_HOST_PASSWORDsubject = subjectsender = settings.EMAIL_FROMreceiver = settings.TEST_EMAIL_TOmsg = MIMEMultipart()part = MIMEText(str(data), 'html')msg.attach(part)msg['from'] = Header('标题,也可以写邮箱账号', 'utf-8')msg['Subject'] = Header(subject, 'utf-8')msg["Accept-Language"] = "zh-CN"msg["Accept-Charset"] = "ISO-8859-1,utf-8"try:server = smtplib.SMTP()server.connect(mail_host)server.login(mail_user, mail_pass)server.sendmail(sender, receiver, msg.as_string())server.quit()except Exception:logger.error(msg=traceback.format_exc())
二,django邮件功能的使用
#settings.py: # qq IMAP/SMTP 配置 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.qq.com' EMAIL_PORT = 25 # 或者 465/587是设置了 SSL 加密方式 # 发送邮件的邮箱 EMAIL_HOST_USER = ‘你的邮箱’ # 在邮箱中设置的客户端授权密码 EMAIL_HOST_PASSWORD = ‘你的IMAP授权码’ # 如果重新设置了新的授权码,直接使用最新的授权码即可 EMAIL_USE_TLS = True # 这里必须是 True,否则发送不成功 # 收件人看到的发件人, 必须是一直且有效的 EMAIL_FROM = ‘Tencent<你的邮箱>' """ # qq POP3/SMTP 配置 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.qq.com' EMAIL_PORT = 110 # 或者 995是设置了 SSL 加密方式 #发送邮件的邮箱 EMAIL_HOST_USER = '你的qq邮箱' #在邮箱中设置的客户端授权密码 EMAIL_HOST_PASSWORD = '你的pop3授权码' # 如果重新设置了新的授权码,直接使用最新的授权码即可 EMAIL_USE_TLS = True # 这里必须是 True,否则发送不成功 #收件人看到的发件人 EMAIL_FROM = ‘Tencent<xxx@qq.com>’ """from django.core.mail import send_mail from django.core.mail import EmailMultiAlternatives #send mail def send_email(file_path, total, typical, dts):html_content = loader.render_to_string('email.html',{'dts': dts,'total': total,'typical': typical})email = EmailMultiAlternatives('title', html_content, settings.EMAIL_FROM, settings.EMAIL_TO)email.attach_file(file_path)email.content_subtype = "html"email.send()
三、发送带图片和附件的邮件
1 import os 2 import datetime 3 import smtplib 4 import logging 5 import traceback 6 from email.mime.multipart import MIMEMultipart 7 from email.mime.image import MIMEImage 8 from email.mime.text import MIMEText 9 from email.header import Header 10 11 def send_img_mail(data, subject, recivers, attach_file=None): 12 base_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) 13 mail_host = settings.EMAIL_HOST 14 mail_user = settings.EMAIL_HOST_USER 15 mail_pass = settings.EMAIL_HOST_PASSWORD 16 subject = subject 17 sender = settings.EMAIL_FROM 18 receiver = recivers 19 20 msg = MIMEMultipart() 21 msg.attach(MIMEText(str(data), 'html')) 22 23 with open(os.path.join(base_dir, 'dist/static/img/zk_header.png'), 'rb') as f: 24 msgImage = MIMEImage(f.read()) 25 msgImage.add_header('Content-ID', '<image1>') 26 msg.attach(msgImage) 27 28 with open(os.path.join(base_dir, 'dist/static/img/zk_footer.jpg'), 'rb') as f: 29 msgImage = MIMEImage(f.read()) 30 msgImage.add_header('Content-ID', '<image2>') 31 msg.attach(msgImage) 32 33 if attach_file: 34 last_month = datetime.datetime.today() - relativedelta(months=1) 35 attachment = MIMEText(open(attach_file, 'rb').read(), 'base64', 'gb2312') 36 attachment["Content-Type"] = 'application/octet-stream' 37 attachment["Content-Disposition"] = 'attachment; filename="XXX产品{0}月新增XX问题.xls"'. \ 38 format(last_month.month) 39 msg.attach(attachment) 40 41 msg['from'] = Header('XXXXXX', 'utf-8') 42 msg['Subject'] = Header(subject, 'utf-8') 43 msg["Accept-Language"] = "zh-CN" 44 msg["Accept-Charset"] = "ISO-8859-1,utf-8" 45 46 try: 47 server = smtplib.SMTP() 48 server.connect(mail_host) 49 server.login(mail_user, mail_pass) 50 server.sendmail(sender, receiver, msg.as_string()) 51 server.quit() 52 except Exception: 53 logger.error(msg=traceback.format_exc())
html文件格式:
<img src="cid:image1"> <img src="cid:image2">
posted on 2018-07-05 15:28 _潜行者 阅读(...) 评论(...) 编辑 收藏