python 发送邮件是自动化中的一个环节,在网上找了一些资料后,发现有一些代码已经不可用,总是报服务器500错误
以下是我尝试用的代码,亲测可用~~~~
方法1:
#coding=utf-8
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
msg_from=*2919*******@qq.com' #发送方邮箱
passwd='XXXXXXX' #填入发送方邮箱的授权码
msg_to='kangkai****@163.com' #收件人邮箱
subject="python邮件测试" #主题
content="hello, this is email content"
msg = MIMEText(content)
msg['Subject'] = subject
msg['From'] = msg_from
msg['To'] = msg_to
zipFile = 'mianshi.zip'
zipApart = MIMEApplication(open(zipFile, 'rb').read())
zipApart.add_header('Content-Disposition', 'attachment', filename=zipFile)
m = MIMEMultipart()
m.attach(zipApart)
s = smtplib.SMTP_SSL("smtp.qq.com",465)
s.login(msg_from, passwd)
s.sendmail(msg_from, msg_to, msg.as_string())
print "发送成功"
s.quit()
方法二:引用 yagmail模块
#coding=utf-8
import yagmail
yag = yagmail.SMTP( user="2919877613@qq.com", password="ozfxgtbrioxtdejh", host='smtp.qq.com',smtp_ssl=True)
#password这个是第三方授权码,不是邮箱密码
#host服务器
#smtp_ssl=True 这段用在一些可能加密的邮箱服务器,比如公司邮箱
contents = ['This is the body, and here is just text http://somedomain/image.png','You can find an audio file attached.', '/local/path/song.mp3']
yag.send('kangkai1324@163.com', 'subject', contents, ["d://log.txt","d://1.png"])
#yag.send 是接收方邮箱地址,可以发送给多个,用","隔开
#subject是题目
#contents是内容
#中括号内是发送的附件
# 1、开通发送方邮件的第三方授权
# 2、安装yagmail库