python发邮件详解_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发送邮件的全部知识点,感谢大家的学习和对脚本之家的支持。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
雷达图(Radar Chart),也称为蜘蛛网图(Spider Chart)或星形图(Star Chart),是一种多变量数据可视化方式,通常用于比较多个变量或维度的相对关系。 Python使用`matplotlib`库可以绘制雷达图。下面我将为你详细讲解如何使用Python绘制雷达图。 首先,我们需要导入相关的库: ```python import numpy as np import matplotlib.pyplot as plt ``` 接下来,我们需要准备数据。假设我们要绘制一个学生的五项能力评估雷达图,其包括语文、数学、英语、体育和艺术五个维度的得分: ```python labels = np.array(['语文', '数学', '英语', '体育', '艺术']) data = np.array([90, 80, 85, 70, 60]) ``` 然后,我们需要计算出每个维度在雷达图的角度。因为雷达图是一个圆形,所以每个维度的角度应该是均分360度,即每个角度应该是`360 / 数据维度个数`。代码如下: ```python angles = np.linspace(0, 2*np.pi, len(labels), endpoint=False) angles = np.concatenate((angles, [angles[0]])) ``` 接下来,我们需要将数据和角度转换成极坐标系下的坐标。这里我们可以使用`np.vstack()`函数将数据和第一个数据点组合起来,再使用`np.cos()`和`np.sin()`函数计算出每个数据点的坐标。代码如下: ```python data = np.concatenate((data, [data[0]])) coords = np.vstack((angles, data)).T coords = np.concatenate((coords, [coords[0]])) ``` 最后,我们可以使用`matplotlib`的`plot()`函数绘制出雷达图。代码如下: ```python fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True)) ax.plot(angles, data, 'o-', linewidth=2) ax.fill(coords[:, 0], coords[:, 1], alpha=0.25) ax.set_thetagrids(angles * 180/np.pi, labels) ax.set_title('学生五项能力评估') ax.grid(True) ``` 完整的代码如下: ```python import numpy as np import matplotlib.pyplot as plt labels = np.array(['语文', '数学', '英语', '体育', '艺术']) data = np.array([90, 80, 85, 70, 60]) angles = np.linspace(0, 2*np.pi, len(labels), endpoint=False) angles = np.concatenate((angles, [angles[0]])) data = np.concatenate((data, [data[0]])) coords = np.vstack((angles, data)).T coords = np.concatenate((coords, [coords[0]])) fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True)) ax.plot(angles, data, 'o-', linewidth=2) ax.fill(coords[:, 0], coords[:, 1], alpha=0.25) ax.set_thetagrids(angles * 180/np.pi, labels) ax.set_title('学生五项能力评估') ax.grid(True) plt.show() ``` 运行代码,我们可以看到绘制出来的雷达图: ![雷达图](https://img-blog.csdnimg.cn/20211104121534521.png) 这个雷达图表示该学生在语文、数学、英语、体育和艺术五个维度上的得分情况,可以用于对比不同学生在这五个维度上的能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值