Python发送邮件的实例代码讲解

yipeiwu_com6年前Python基础

一、邮件发送示例

邮件发送示例

flask_email及smtplib原生邮件发送示例,适用于基于Flask框架开发,但是内部设置的定时任务发送邮件/或提供离线接口发送邮件操作

1.flask config配置

# QQ邮箱配置
MAIL_DEBUG = True # 开启debug,便于调试看信息
MAIL_SUPPRESS_SEND = False # 发送邮件,为True则不发送
MAIL_SERVER = 'smtp.qq.com' # 邮箱服务器
MAIL_PORT = 465 # 端口
MAIL_USE_SSL = True # 重要,qq邮箱需要使用SSL
MAIL_USE_TLS = False # 不需要使用TLS
MAIL_USERNAME = '@qq.com' # 填邮箱
MAIL_PASSWORD = '' # 填授权码
FLASK_MAIL_SENDER = '@qq.com' # 邮件发送方
FLASK_MAIL_SUBJECT_PREFIX = '' # 邮件标题
MAIL_DEFAULT_SENDER = '@qq.com' # 填邮箱,默认发送者

2.示例代码

import smtplib
import constant # 定义常量文件
from email.header import Header
from email.mime.text import MIMEText

constant.SMTP_SERVER = 'smtp.qq.com'
constant.PORT = 465


class EmailSender(object):
  def __init__(self, subject, receivers, sender='ss@qq.com', password='123456', offline=False, html_body=None,
         text_body=None, **kwargs):
    self.subject = subject
    self.receivers = receivers
    self.sender = sender
    self.password = password
    if offline:
      if html_body:
        self.send_body = html_body
        self._subtype = 'html'
      elif text_body:
        self.send_body = text_body
        self._subtype = 'plain'
      self.send_email_offline()
    else:
      from flask_mail import Mail
      self.mail = Mail()
      dic = dict(kwargs)
      self.send_email(html_body, text_body, attachments=dic.get("attachments"), sync=dic.get("sync"))

  def send_email_offline(self):
    try:
      message = MIMEText(self.send_body, self._subtype, 'utf-8')
      message['From'] = self.sender
      message['To'] = ','.join(self.receivers)
      message['Subject'] = Header(self.subject, 'utf-8')
      smtpObj = smtplib.SMTP_SSL(constant.SMTP_SERVER, constant.PORT)
      smtpObj.login(self.sender, self.password)
      smtpObj.sendmail(
        self.sender, self.receivers, message.as_string())
      smtpObj.quit()
    except smtplib.SMTPException:
      return "smtp服务器发送异常 >> 无法发送邮件"
    except Exception as e:
      return f"邮件发送失败 >> {e}"

  def send_email(self, text_body, html_body, attachments=None, sync=False):
    from threading import Thread
    from flask import current_app
    from flask_mail import Message
    try:
      msg = Message(self.subject, recipients=self.receivers)
      msg.body = text_body
      msg.html = html_body
      if attachments:
        for attachment in attachments:
          msg.attach(*attachment)
      if not sync:
        self.mail.send(msg)
      else:
        Thread(target=self.send_async_email, args=(current_app._get_current_object(), msg)).start()
    except Exception as e:
      return f"邮件发送失败 >> {e}"

  def send_async_email(self, app, msg):
    with app.app_context():
      try:
        self.mail.send(msg)
      except Exception as e:
        print(f"邮件发送错误信息:{e}")

3.使用

err = EmailSender(subject='吃货询问', receivers=["123@qq.com", "1234@qq.cn"], text_body='吃了没呀?', offline=True)
if err:
  print(err)

以上3点就是关于Python发送邮件的全部知识点,感谢大家的学习和对【听图阁-专注于Python设计】的支持。

相关文章

正则给header的冒号两边参数添加单引号(Python请求用)

正则给header的冒号两边参数添加单引号(Python请求用)

正则给header的冒号两边参数添加单引号(Python请求用) 直接从浏览器Chrome复制header值如下: Host: kyfw.12306.cn Connection:...

使用celery执行Django串行异步任务的方法步骤

前言 Django项目有一个耗时较长的update过程,希望在接到请求运行update过程的时候,Django应用仍能正常处理其他的请求,并且update过程要求不能并行,也不能漏掉任何...

Python排序搜索基本算法之堆排序实例详解

Python排序搜索基本算法之堆排序实例详解

本文实例讲述了Python排序搜索基本算法之堆排序。分享给大家供大家参考,具体如下: 堆是一种完全二叉树,堆排序是一种树形选择排序,利用了大顶堆堆顶元素最大的特点,不断取出最大元素,并调...

Python装饰器原理与基本用法分析

本文实例讲述了Python装饰器原理与基本用法。分享给大家供大家参考,具体如下: 装饰器: 意义:在不能改变原函数的源代码,和在不改变整个项目中原函数的调用方式的情况下,给函数添加新的功...

Python使用贪婪算法解决问题

Python使用贪婪算法解决问题 集合覆盖问题 假设你办了个广播节目,要让全美50个州的听众都收听到。为此,你需要决定在哪些广播台播出。在每个广播台播出都需要支出费用,因此你力图在尽可...