运行环境:
python2.7
,python3.x
的话,把代码中的中文的字符前的u
去掉就好,这是2与3基本的区别
- # -*- coding: utf-8 -*-
- import smtplib
- import email.MIMEMultipart # import MIMEMultipart
- import email.MIMEText # import MIMEText
- import email.MIMEBase # import MIMEBase
- import os.path
- import mimetypes
- import datetime
- import os
- from email.header import Header
- # today = datetime.date.today()
- # yesterday = today - datetime.timedelta(days=1)
- From = "%s <*****>" % Header("xxx","utf-8") # 发送邮箱,*****是发送来源的邮箱,xxx是发送邮件时候的标题,
- To = " ###" # 接受邮件的邮箱
- file_name = "***" # 附件名(带路径)
- server = smtplib.SMTP_SSL("smtp.exmail.qq.com", 465)
- server.login("*****", "password or 授权码") # 仅smtp服务器需要验证时
- # 构造MIMEMultipart对象做为根容器
- main_msg = email.MIMEMultipart.MIMEMultipart()
- # 构造MIMEText对象做为邮件显示内容并附加到根容器
- important = """
- 这里面写内容
- """
- text_msg = email.MIMEText.MIMEText("这是内容的标题" + '\n' + important, _charset="utf-8")
- text_msg["Accept-Language"] = "zh-CN"
- text_msg["Accept-Charset"]="ISO-8859-1,utf-8"
- main_msg.attach(text_msg)
- # 设置有中文的字符串,在微软的outlook中乱码,所以才有了上面对中文的设置
- # 构造MIMEBase对象做为文件附件内容并附加到根容器
- ## 读入文件内容并格式化 [方式1]------------------------------
- data = open(file_name, 'rb')
- ctype, encoding = mimetypes.guess_type(file_name)
- if ctype is None or encoding is not None:
- ctype = 'application/octet-stream'
- maintype, subtype = ctype.split('/', 1)
- file_msg = email.MIMEBase.MIMEBase(maintype, subtype)
- file_msg.set_payload(data.read())
- data.close()
- email.Encoders.encode_base64(file_msg) # 把附件编码
- ## 设置附件头
- basename = os.path.basename(file_name)
- file_msg.add_header('Content-Disposition', 'attachment', filename=basename) # 修改邮件头
- main_msg.attach(file_msg)
- # 设置根容器属性
- subject = u" 邮件标题"
- if not isinstance(subject,unicode):
- subject = unicode(subject)
- main_msg['From'] = From
- main_msg['To'] = To
- main_msg['Subject'] = subject
- main_msg['Date'] = email.Utils.formatdate()
- # 得到格式化后的完整文本
- fullText = main_msg.as_string()
- # print('发送成功')
- # 用smtp发送邮件
- try:
- server.sendmail(From, To, fullText)
- finally:
- server.quit()
本文作者为olei,转载请注明。