python实现邮件接口——smtplib模块

时间:2021-05-29 18:14:16

1.发送字符串的邮件

import smtplib
from email.mime.text import MIMEText
#设置服务器所需信息
#163邮箱服务器地址
mail_host = 'smtp.163.com'
#163用户名
mail_user = '137####8754'
#密码(部分邮箱为授权码)
mail_pass = 'SHANG######022'
#邮件发送方邮箱地址
sender = '137#####754@163.com'
#邮件接受方邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发
receivers = ['84#####53@qq.com']

#设置email信息
#邮件内容设置
message = MIMEText('这是一封测试的邮件','plain','utf-8')
#邮件主题
message['Subject'] = 'title'
#发送方信息
message['From'] = sender
#接受方信息
message['To'] = receivers[0]

#登录并发送邮件
try:
    smtpObj = smtplib.SMTP()
    #连接到服务器
    smtpObj.connect(mail_host,25)
    #登录到服务器
    smtpObj.login(mail_user,mail_pass)
    #发送
    smtpObj.sendmail(
        sender,receivers,message.as_string())
    #退出
    smtpObj.quit()
    print('success')
except smtplib.SMTPException as e:
    print('error',e) #打印错误

 2.发送带附件的邮件

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage

#设置登录及服务器信息
#163邮箱服务器地址
mail_host = 'smtp.163.com'
#163用户名
mail_user = '13#####54'
#密码(部分邮箱为授权码)
mail_pass = 'SH#######g022'
#邮件发送方邮箱地址
sender = '13#####54@163.com'
#邮件接受方邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发
receivers = ['8#######53@qq.com']

#设置eamil信息
#添加一个MIMEmultipart类,处理正文及附件
message = MIMEMultipart()
message['From'] = sender
message['To'] = receivers[0]
message['Subject'] = '这是一个测试的邮件'
#推荐使用html格式的正文内容,这样比较灵活,可以附加图片地址,调整格式等
with open('demo.html','r',encoding="utf-8") as f:
    content = f.read()
#设置html格式参数
part1 = MIMEText(content,'html','utf-8')
#添加一个txt文本附件
with open('shang.txt','r',encoding="utf-8")as h:
    content2 = h.read()
#设置txt参数
part2 = MIMEText(content2,'plain','utf-8')
#附件设置内容类型,方便起见,设置为二进制流
part2['Content-Type'] = 'application/octet-stream'
#设置附件头,添加文件名
part2['Content-Disposition'] = 'attachment;filename="shang.txt"'
#添加照片附件
with open('timg.jpg','rb')as fp:
    picture = MIMEImage(fp.read())
    #与txt文件设置相似
    picture['Content-Type'] = 'application/octet-stream'
    picture['Content-Disposition'] = 'attachment;filename="timg.jpg"'
#将内容附加到邮件主体中
message.attach(part1)
message.attach(part2)
message.attach(picture)

#登录并发送
try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host,25)
    smtpObj.login(mail_user,mail_pass)
    smtpObj.sendmail(
        sender,receivers,message.as_string())
    print('success')
    smtpObj.quit()
except smtplib.SMTPException as e:
    print('error',e)

 

 

参考博客https://www.cnblogs.com/GavinSimons/p/9136663.html

相关文章