• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

如何利用python发送邮件

python 搞代码 4年前 (2022-01-09) 13次浏览 已收录 0个评论

一、zmial发送邮件

zmial是第三方库,需进行安装

pip install zmail

完成后,来给发一封邮件

subject:标题
content_text:内容

 import zmail
 server = zmail.server('发件人邮箱地址','授权码')
 
 server.send_mail('收件人邮箱地址',{'subject':'Hello!','content_text':'By zmail.'})

二、smtplib发送邮件

import smtplib
from email.mime.text import MIMEText
#--------发件相关参数--------
smtpserver="smtp.qq.com"  #连接服务器
port = 465          <i>本文来源gaodai$ma#com搞$代*码*网</i> #端口
sender = "[email protected]"#账号
psw = "xxxxx"#密码 授权码
receiver="[email protected]"#接收人

#--------编辑邮件内容--------

subject="qq邮件主题"
body= '<p>这个是发送的qq邮件</p>'
msg = MIMEText(body,'html','utf-8')
msg['from']=sender
msg['to']='[email protected]'
msg['subject']=subject

#-----------test_email-------
smtp = smtplib.SMTP_SSL(smtpserver,port)#连接服务器
smtp.login(sender,psw)#登录
smtp.sendmail(sender,receiver,msg.as_string())#发送邮件
smtp.quit()

三、发送带附件的邮件

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import os

smtpserver='smtp.qq.com'
port =465
sender='[email protected]'
psw = 'xxxx'
recevier = "[email protected]"

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 发送邮件的资料请关注搞代码其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:如何利用python发送邮件
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址