python3之发送邮件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3之发送邮件相关的知识,希望对你有一定的参考价值。
#/usr/bin/env python3 # encoding: utf-8 #@author: Lejie #@software: PyCharm Community Edition #@file: learn_smtp.py #@time: 2017/6/26 16:29 import smtplib import email.mime.multipart import email.mime.text from email.mime.application import MIMEApplication msg = email.mime.multipart.MIMEMultipart() #定义邮件对象 # print(msg,type(msg)) msg[‘from‘] = ‘[email protected]‘ #必须和login的账号一样 msg[‘to‘] = ‘[email protected],[email protected]‘ msg[‘subject‘] = ‘test‘ #邮件内容 ###直接定义 content = ‘‘‘ 你好, 这是一封测试邮件。 ‘‘‘ ###从文件读取内容 content1 = open(‘tt.log‘,‘rb‘).read() #以rb来读取文件内容,可以识别中文 ###插入文本 txt = email.mime.text.MIMEText(content1,‘html‘,‘utf-8‘) #html 类型 # txt = email.mime.text.MIMEText(content1,‘plain‘,‘utf-8‘) #txt类型 msg.attach(txt) #文本附件 MIMEText ,这种方式文本内容会在显示在邮件内容里 # att1 = email.mime.text.MIMEText(open(‘tt.log‘, ‘rb‘).read(), ‘base64‘, ‘utf-8‘) # att1["Content-Type"] = ‘application/octet-stream‘ # att1["Content-Disposition"] = ‘attachment;filename="test.txt"‘ # msg.attach(att1) #添加附件 MIMEApplication 支持大部分图片格式,pdf,excel,mp3,txt等等 att2 = MIMEApplication(open(‘tt.log‘,‘rb‘).read()) #filename指定的名字跟实体文件名没有关系可以任意指定 att2.add_header(‘Content-Disposition‘,‘attachment‘,filename="t.log") msg.attach(att2) # #配置smtp smtp = smtplib # smtp = smtplib.SMTP() #不加密 # smtp.connect(‘smtp.exmail.qq.com‘, ‘25‘) smtp = smtplib.SMTP_SSL() #加密 smtp.connect(‘smtp.exmail.qq.com‘, ‘465‘) try: #验证 smtp.login(‘[email protected]‘, ‘[email protected]‘) #发送 smtp.send_message(msg) #不用指定from,to # smtp.sendmail(‘[email protected]‘, ‘[email protected]‘, str(msg)) #必须指定from,to print("发送成功") except Exception as e: print(e) smtp.quit()
以上是关于python3之发送邮件的主要内容,如果未能解决你的问题,请参考以下文章