Python发送邮件的实例代码讲解
作者:初遇ぃ 时间:2021-06-05 02:35:10
一、邮件发送示例
邮件发送示例
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发送邮件的全部知识点,感谢大家的学习和对脚本之家的支持。
来源:https://www.cnblogs.com/zhangliang91/p/11684551.html
标签:Python,发送邮件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
PyCharm 2020 激活到 2100 年的教程
2021-01-19 12:30:43
![](https://img.aspxhome.com/file/2023/7/80627_0s.jpg)
朋友去一家游戏公司的机试题,被难住了
2009-11-29 15:23:00
vscode写python时的代码错误提醒和自动格式化的方法
2023-02-25 12:54:59
![](https://img.aspxhome.com/file/2023/2/114682_0s.jpg)
python简单实现获取当前时间
2022-08-28 16:38:49
sql 存储过程分页代码 支持亿万庞大数据量
2011-09-30 11:16:46
解读ASP.NET 5 & MVC6系列教程(6):Middleware详解
2023-07-23 22:27:34
Python使用文件锁实现进程间同步功能【基于fcntl模块】
2022-07-04 17:45:15
深入分析SQL Server的数据转换服务
2008-11-28 15:29:00
python pandas中的agg函数用法
2023-07-20 09:40:08
![](https://img.aspxhome.com/file/2023/8/61178_0s.png)
Python实现京东抢秒杀功能
2021-12-06 04:50:17
![](https://img.aspxhome.com/file/2023/8/71558_0s.png)
python控制台显示时钟的示例
2023-10-23 12:04:24
python中h5py开源库的使用样例详解
2022-03-30 00:37:03
Django 后台带有字典的列表数据与页面js交互实例
2021-12-01 01:59:39
详解Python中Sync与Async执行速度快慢对比
2023-02-06 13:26:45
![](https://img.aspxhome.com/file/2023/8/92138_0s.png)
DHTML实例解析:用HTC统一定制表单样式
2007-11-04 18:48:00
Linux 创建oracle数据库的详细过程
2023-07-14 15:59:09
![](https://img.aspxhome.com/file/2023/8/64438_0s.jpg)
Python操作sqlite3快速、安全插入数据(防注入)的实例
2022-04-22 16:38:14
存贮查询与运行时查询孰优孰劣?
2009-11-01 15:13:00
python GUI库图形界面开发之PyQt5美化窗体与控件(异形窗体)实例
2023-07-19 00:34:06
![](https://img.aspxhome.com/file/2023/3/112793_0s.png)
解决Tensorflow占用GPU显存问题
2021-09-01 14:34:46
![](https://img.aspxhome.com/file/2023/5/81735_0s.jpg)