python发送邮件,亲测可用。

来源:互联网 发布:php 判断域名 编辑:程序博客网 时间:2021/12/08 08:47

1.首先要引入必要的包。

import smtplib
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart
import datetime

2.定义发送邮件函数

def Send_Mail (Message):
TODAY = datetime.date.today()
CURRENTDAY=TODAY.strftime(‘%Y-%m-%d’)
msg = MIMEMultipart()
”’
att = MIMEText(open(r’D:\report\aa.xlsx’, ‘rb’).read(), ‘base64’, ‘gb2312’) #设置附件的目录
att[‘content-type’] = ‘application/octet-stream’
att[‘content-disposition’] = ‘attachment;filename=”IMD_EBM.xlsx”’ #设置附件的名称
msg.attach(att)
”’
content = str(Message) #正文内容
body = MIMEText(content,’plain’,’utf-8’) #设置字符编码
msg.attach(body)
msgto = ‘835232404@qq.com’ # 收件人地址 多个联系人,格式[‘aa@163.com’; ‘bb@163.com’]
msgfrom = ‘1074321997@qq.com’ # 寄信人地址 ,
msg[‘subject’] = ‘Finish at ’ #主题
msg[‘date’]=time.ctime() #时间
#msg[‘Cc’]=’bb@junbao.net’ #抄送人地址 多个地址不起作用
mailuser = ‘1074321997@qq.com’ # 用户名
mailpwd = ‘wangzijia1990’ #密码
try:
smtp = smtplib.SMTP()
smtp.connect(r’smtp.qq.com’)# smtp设置
smtp.login(mailuser, mailpwd) #登录
smtp.sendmail(msgfrom, msgto, msg.as_string()) #发送
smtp.close()
print “success mail”
except Exception, e:
print e,u”失败了”

0 0