电子邮件
python发送电子邮件时,使用标准库中的smtplib和email,smptlib中有一个SMTP类,需要发送邮件时,初始化该类返回smtpserver对象,使用login登陆MUA,使用sendmail方法发送邮件,邮件的正文用email.mime.text.MIMEText对象进行描述
简单电子邮件发送程序
from email.mime.text import MIMEText
msg = MIMEText('hello message','plain', 'utf-8')
from_addr = 'yourPhone@163.com'
to_addr = 'yourQQ@qq.com'
sub_msg = 'hello'
smtp_server = 'smtp.163.com'
import smtplib
# 初始化smtp对象,传入服务器地址与端口号
server = smtplib.SMTP(smtp_server,25)
# 设置调试模式可以让我们看到发送邮件过程中的信息
server.set_debuglevel(1)
# 登陆MUA,使用账户与授权码登陆
server.login(from_addr, 'yourpassword')
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = 'important message'
server.sendmail(from_addr, [to_addr], msg.as_string())
邮件被放入垃圾邮件中,如下
发送带附件的电子邮件
from email.mime.text import MIMEText
from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from_addr = '18392136027@163.com'
to_addr = '1786614260@qq.com'
smtp_server = 'smtp.163.com'
smtp_port = 25
subject_msg = 'subject'
mul_msg = MIMEMultipart()
mul_msg['From'] = from_addr
mul_msg['To'] = to_addr
mul_msg['Subject'] = subject_msg
msg = MIMEText('\n\rimportant message\n\r', 'plain', 'utf-8')
mul_msg.attach(msg)
att1 = MIMEText(open('program.txt','rb').read(), 'base64', 'utf-8')
att1['Content-Type'] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment;filename="program.txt"'
mul_msg.attach(att1)
smtp = SMTP(smtp_server, smtp_port)
smtp.login(from_addr, 'youpass')
smtp.set_debuglevel(1)
smtp.sendmail(from_addr, to_addr, mul_msg.as_string())
smtp.close()
使用第三方开源库yagmail发送电子邮件
import yagmail
yag = yagmail.SMTP(user='youQQ@qq.com', password='you pass', host='smtp.qq.com', port=25)
contents = ['import message','program.txt']
yag.send(to='dest', subject='subject', contents=contents)
使用pop3协议用网易邮箱发送邮件时,容易被网易识别为垃圾邮件,可以使用qq邮箱