1.发送HTML格式的邮件
与http://www.cnblogs.com/laoguigui/p/7363768.html自动发邮件不太一样,本文利用Python的smtplib模块来发送邮件:
import smtplib from email.mime.text import MIMEText from email.header import Header #发送邮箱服务器 smtpserver = 'smtp.163.com' #发送邮箱用户/密码 user = '***@163.com' password = '***' #发送邮箱 sender = '***@163.com' #接收邮箱 receiver = '***@qq.com' #发送邮件主题 subject = 'test' #编写HTML类型的邮件正文 msg = MIMEText('<html><h1>你好!</h1></html>','html','utf-8') #Header定义邮件标题 msg['Subject'] = Header(subject,'utf-8') msg['From'] = '***@163.com' msg['To'] = "***@qq.com" #连接发送邮件 smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.login(user,password) smtp.sendmail(sender,receiver,msg.as_string()) smtp.quit()
msg['From'] = '***@163.com'
msg['To'] = "***@qq.com"
这两句不写的话会出现smtplib.SMTPDataError: (554, b'DT:SPM 163 smtp12,问题,加上之后邮件就发成功了。
2.发送带附件的邮件
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header #发送邮箱服务器 smtpserver = 'smtp.163.com' #发送邮箱用户/密码 user = '***@163.com' password = '***' #发送邮箱 sender = '***@163.com' #接收邮箱 receiver = '***@qq.com' #发送邮件主题 subject = '中文' #发送的附件 sendfile = open('C:\Users\Administrator\Desktop\pythonweb\test_project\report\login.txt','rb').read() att = MIMEText(sendfile,'base64','utf-8') att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="login.txt"' msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject msgRoot.attach(att) msgRoot['From'] = '***@163.com' msgRoot['To'] = "***@qq.com" #连接发送邮件 smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.login(user,password) smtp.sendmail(sender,receiver,msgRoot.as_string()) smtp.quit()