python发送邮件
发送简单邮件
使用第三方邮件服务商的SMTP服务发送邮件(本文中使用QQ邮箱的SMTP服务)
授权码获取:登录QQ邮箱->点击设置->点击账户->POP3/IMAP/SMTP.../CalDAV服务菜单下点击生成授权码,将生成的授权码作为密码
import smtplib from email.mime.text import MIMEText from email.utils import formataddr send_mail = 'xxxxxxx@qq.com' #发件人邮箱账号 send_pwd = 'xxxxxxx' #发件人邮箱密码 授权码 receiv_mail = 'xxxxxxx@qq.com' #收件人邮箱账号 msg = MIMEText('这是一封测试邮件','plain','utf-8') #邮件正文 msg['From'] = formataddr(['Fromxxx',send_mail]) #发件人昵称,邮箱账号 msg['To'] = formataddr(['to',receiv_mail]) #收件人昵称,邮箱账号 msg['Subject'] = '测试邮件' #邮件主题 server = smtplib.SMTP_SSL('smtp.qq.com',465) #发件人邮箱中的SMTP服务器,端口号为465 server.login(send_mail,send_pwd) #发件邮箱账号、密码 server.sendmail(send_mail,[receiv_mail,],msg.as_string()) #发送邮件 server.quit() #关闭连接
发送HTML格式的邮件
import smtplib from email.mime.text import MIMEText from email.header import Header send_mail = 'xxxxx@qq.com' send_pwd = 'xxxxx' receiv_mail = 'xxxxx@qq.com' mail_msg =''' <p>这是一封测试邮件</p> <p><a href="">点我激活</a></p> ''' msg = MIMEText(mail_msg,'html','utf-8') msg['From'] = Header('测试邮件','utf-8') msg['To'] = Header('测试','utf-8') subject = '发送HTML格式的邮件' msg['Subject'] = Header(subject,'utf-8') server = smtplib.SMTP_SSL('smtp.qq.com',465) server.login(send_mail,send_pwd) server.sendmail(send_mail,[receiv_mail,],msg.as_string()) server.quit()
发送带附件的邮件
import smtplib from email.mime.text import MIMEText from email.header import Header from email.mime.multipart import MIMEMultipart send_mail = 'xxxxx@qq.com' send_pwd = 'xxxxx' receive_mail = 'xxxxx.com' msg = MIMEMultipart() msg['From'] = Header('测试邮件','utf-8') msg['To'] = Header('测试','utf-8') subject = '邮件' msg['Subject'] = Header(subject,'utf-8') msg.attach(MIMEText('这是一封测试附件的邮件','plain','utf-8')) #邮件正文 att1 = MIMEText(open('text.txt','rb').read(),'base64','utf-8') #附件1 att1['Content-Type'] = 'application/octet-stream' att1['Content-Disposition'] = 'attachment;filename="text.txt"' msg.attach(att1) server = smtplib.SMTP_SSL('smtp.qq.com',465) server.login(send_mail,send_pwd) server.sendmail(send_mail,[receive_mail,],msg.as_string()) server.quit()
在HTML中添加图片
import smtplib from email.mime.text import MIMEText from email.header import Header from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart send_mail = 'xxxxx@qq.com' send_pwd = 'xxxxx' receiv_mail = 'xxxxx@qq.com' msg = MIMEMultipart('related') msg['From'] = Header('测试邮件','utf-8') msg['To'] = Header('测试','utf-8') subject = '发送HTML格式的邮件' msg['Subject'] = Header(subject,'utf-8') msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative) mail_msg =''' <p>这是一封添加图片的测试邮件</p> <p>图片演示:</p> <p><img src='cid:image1'></p> ''' msgAlternative.attach(MIMEText(mail_msg,'html','utf-8')) pic = open('123.png','rb') msgImage = MIMEImage(pic.read()) pic.close() msgImage.add_header('Content-ID','<image1>') msg.attach(msgImage) server = smtplib.SMTP_SSL('smtp.qq.com',465) server.login(send_mail,send_pwd) server.sendmail(send_mail,[receiv_mail,],msg.as_string()) server.quit()