#coding: utf-8
import time
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.utils import parseaddr, formataddr
import smtplib
weekday_dist={'Monday':'星期一','Tuesday':'星期二','Wednesday':'星期三','Thursday':'星期四','Friday':'星期五','Saturday':'星期六','Sunday':'星期日'}
from_addr = '***@163.com'
password = '***'
timestamp=time.time()
today=time.strftime('%Y%m%d',time.localtime(timestamp))
weekday=time.strftime('%A',time.localtime(timestamp))
week_day=weekday_dist[weekday]
smtp_server = 'smtp.163.com'#SMTP服务器地址
subject = ' 今天是'+today+'('+week_day+')'#邮件主题
to_list = ['***@qq.com']#收件人
cc_list = ['***@qq.com']#抄送人
def sendMail():
content=getContent()
msg = MIMEMultipart()
msg.attach(MIMEText(content, 'html', 'utf-8'))
msg['Subject'] = Header(subject, 'utf-8').encode()#添加邮件主题
msg['To'] = ";".join(to_list)#添加收件人
msg['Cc'] = ";".join(cc_list)#添加抄送人
msg.attach(addimg("/Users/username/test.jpg","image"))#添加图片到对应的imgid处
server = smtplib.SMTP()
server.connect(smtp_server)
server.starttls() #加密SMTP
server.set_debuglevel(1)
server.login(from_addr,password)
server.sendmail(from_addr, to_list+cc_list, msg.as_string())
server.quit()
#邮件内容
def getContent():
content="<p style='font-family:Microsoft YaHei; font-size:25px; font-weight:bold'>"+subject+"</p>"
content="<img src='cid:image' width='30%'/>"
return content
#读取图片
def addimg(src,imgid): #文件路径、图片id
fp = open(src, 'rb') #打开文件
msgImage = MIMEImage(fp.read()) #读入 msgImage 中
fp.close() #关闭文件
msgImage.add_header('Content-ID', imgid)
return msgImage
if __name__=='__main__':
sendMail()
163可直接使用上述代码发邮件,qq邮箱需求去邮箱开启smtp权限
(我发了几次这个邮件做测试之后,我的邮件开始被识别为垃圾邮件了。。。。。)