使用python发送邮件的流程:
1、获得smtp服务
2、连接服务器
3、模拟客户端登录
4、实现邮件发送
5、退出登录
发送不带附件邮件
from email.mime.text import MIMEText
import smtplib
msg = MIMEText(‘hello,this is a mail...’,’plain’,’utf-8’)
参数:邮件正文、‘plain’表示纯文本、utf-8编码
msg[‘From’] = _formate_addr(‘发送者’)
msg[‘To’] = _format_addr(‘接收者’)
msg[‘Subject’] = ‘邮件主题’
server = smtplib.SMTP()
server.set_debuglevel(1)
server.connect(smtp_server,25)
server.login(发送者帐号,发送者密码)
server.sendmail(发送者帐号,接收地址,str(msg))
server.quit()
发送带附件邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import
MIMEMultipart
from email.mime.application import
MIMEApplication
msg = MIMEMultipart()
msg[‘From’] = _formate_addr(‘发送者’)
msg[‘To’] = _format_addr(‘接收者’)
msg[‘Subject’] = ‘邮件主题’
#纯文本部分
msg.attach(MIMEText(‘hello,this is a mail...’,’plain’,’utf-8’)
#首先是xlsx类型的附件
xlsxpart =MIMEApplication(open('test.xlsx', 'rb').read())
xlsxpart.add_header('Content-Disposition','attachment', filename='test.xlsx')
msg.attach(xlsxpart)
# jpg类型的附件
jpgpart = MIMEApplication(open('beauty.jpg','rb').read())
jpgpart.add_header('Content-Disposition','attachment', filename='beauty.jpg')
msg.attach(jpgpart)
# mp3类型的附件
mp3part = MIMEApplication(open('kenny.mp3','rb').read())
mp3part.add_header('Content-Disposition','attachment', filename='benny.mp3')
msg.attach(mp3part)
server = smtplib.SMTP()
server.set_debuglevel(1)
server.connect(smtp_server,25)
server.login(发送者帐号,发送者密码)
server.sendmail(发送者帐号,接收地址,str(msg))
server.quit()