简介

"text-align: center">python3实现SMTP发送邮件详细教程

"text-align: center">python3实现SMTP发送邮件详细教程

Demo

import smtplib
from email.header import Header
from email.mime.text import MIMEText

# 第三方 SMTP 服务
mail_host = "smtp.163.com"   # SMTP服务器
mail_user = "***"         # 用户名
mail_pass = "***"        # 授权密码,非登录密码

sender = ***@163.com'  # 发件人邮箱(最好写全, 不然会失败)
receivers = [***@qq.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

content = '我用Python'
title = '人生苦短' # 邮件主题

def sendEmail():

  message = MIMEText(content, 'plain', 'utf-8') # 内容, 格式, 编码
  message['From'] = "{}".format(sender)
  message['To'] = ",".join(receivers)
  message['Subject'] = title

  try:
    smtpObj = smtplib.SMTP_SSL(mail_host, 465) # 启用SSL发信, 端口一般是465
    smtpObj.login(mail_user, mail_pass) # 登录验证
    smtpObj.sendmail(sender, receivers, message.as_string()) # 发送
    print("mail has been send successfully.")
  except smtplib.SMTPException as e:
    print(e)

def send_email2(SMTP_host, from_account, from_passwd, to_account, subject, content):
  email_client = smtplib.SMTP(SMTP_host)
  email_client.login(from_account, from_passwd)
  # create msg
  msg = MIMEText(content, 'plain', 'utf-8')
  msg['Subject'] = Header(subject, 'utf-8') # subject
  msg['From'] = from_account
  msg['To'] = to_account
  email_client.sendmail(from_account, to_account, msg.as_string())

  email_client.quit()

if __name__ == '__main__':
  sendEmail()
  # receiver = '***'
  # send_email2(mail_host, mail_user, mail_pass, receiver, title, content)

刚开始测试时,第一次发送邮件是成功的,但是后面再次测试时却出现了提示554,根据给出的网址查看错误代码 

554 DT:SPM 发送的邮件内容包含了未被许可的信息,或被系统识别为垃圾邮件。请检查是否有用户发送病毒或者垃圾邮件。如下图所示:

python3实现SMTP发送邮件详细教程

针对该问题,究竟如何解决,会在下一篇博文中进行展开。若看到的朋友有好的解决方法,还请提出,在此感谢。

附 参考资料

附 电子书福利(免积分下载)

《Flask Web开发:基于Python的Web应用开发实战》

《Learning Python, 5th Edition》

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com