Python发送邮件的两种实现方式:zmail与smtplib详解
本文详细介绍Python中发送邮件的两种主流方法。首先讲解第三方库zmail的简易安装与使用,包括基础邮件发送;随后深入原生smtplib模块,演示如何配置SMTP服务器、构建邮件对象,并重点解析发送带附件邮件的完整代码逻辑与参数设置,帮助开发者快速掌握Python邮件自动化技能。
使用zmail库简化邮件发送
一、使用zmail发送邮件
zmail是一个第三方库,使用前需通过pip进行安装。
pip install zmail
安装完成后,即可尝试发送一封测试邮件。
其中,subject参数用于指定邮件标题,content_text参数用于定义邮件正文内容。
import zmail
server = zmail.server('发件人邮箱地址','授权码')
server.send_mail('收件人邮箱地址',{'subject':'Hello!','content_text':'By zmail.'})
使用smtplib模块发送基础邮件
二、使用smtplib发送邮件
import smtplib
from email.mime.text import MIMEText
#--------发件相关参数--------
smtpserver="smtp.qq.com" #连接服务器
port = 465 #端口
sender = "741841851@qq.com"#账号
psw = "xxxxx"#密码 授权码
receiver="741841851@qq.com"#接收人
#--------编辑邮件内容--------
subject="qq邮件主题"
body= '<p>这个是发送的qq邮件</p>'
msg = MIMEText(body,'html','utf-8')
msg['from']=sender
msg['to']='741841851@qq.com'
msg['subject']=subject
#-----------test_email-------
smtp = smtplib.SMTP_SSL(smtpserver,port)#连接服务器
smtp.login(sender,psw)#登录
smtp.sendmail(sender,receiver,msg.as_string())#发送邮件
smtp.quit()
通过smtplib发送带附件的邮件
三、发送带附件的邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import os
smtpserver='smtp.qq.com'
port =465
sender='741841851@qq.com'
psw = 'xxxx'
recevier = "741841851@qq.com"
filenamepath = os.path.join(os.path.dirname(os.path.realpath(__file__)),'ceshi.html')
with open(filenamepath,'rb') as f:
mail_body=f.read().decode('utf-8')
msg = MIMEMultipart()
msg['from']=sender#发件人
msg['to']=recevier#收件人
msg['subject']='这是我的主题99'#主题
# 正文
body = MIMEText(mail_body,'html','utf-8')
msg.attach(body)
#附件
att = MIMEText(mail_body,'base64','gbk')#用utf-8会出现乱码
att['Content-Type']='application/octet-stream'
att['Content-Disposition']='attachment;filename="test_report.html"'
msg.attach(att)
####发送邮件
try:
smtp = smtplib.SMTP()
smtp.connect(smtpserver)#连接服务器
smtp.login(sender,psw)#登录
except:
smtp = smtplib.SMTP_SSL(smtpserver,port)
smtp.login(sender,psw)#登录
smtp.sendmail(sender,recevier,msg.as_string())#发送邮件
smtp.quit()
以上即为利用Python发送邮件的详细内容,更多关于Python发送邮件的资料请关注本站其它相关文章!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













