python实现基于smtp发送邮件_在线工具

2022年5月10日09:56:50

【前言】

在某些项目中,我们需要实现发送邮件的功能,比如:

  1. 爬虫结束后,发送邮件通知
  2. 定时发送邮件提醒待办事项
  3. 某项业务逻辑触发邮件通知

今天我们就分享如何基于smtp借助163邮箱来发送邮件

【实现过程】

163邮箱配置

首先登录163邮箱进行配置(没有请先注册):https://email.163.com/

配置SMTP服务开启(需要发送短信验证码进行开通)

python实现基于smtp发送邮件_在线工具

开始编写脚本

新建python脚本 email_163.py
添加 smtp 模块

import smtplib
from email.mime.text import MIMEText

编写代码实现

from datetime import datetime
import smtplib
from email.mime.text import MIMEText
from config import settings as st

def send_mail_plain(receivers, subject, content):
    #163邮箱服务器地址
    mail_host = 'smtp.163.com'
    #163用户名
    mail_user = st.mail_user_163
    #密码(部分邮箱为授权码)
    mail_pass = st.mail_password_163
    #邮件发送方邮箱地址
    sender = st.mail_sender_163
    #邮件接受方邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发
    receivers = receivers
    #邮件内容设置
    message = MIMEText(content, 'plain', 'utf-8')
    #邮件主题
    message['Subject'] = subject
    #发送方信息
    message['From'] = sender
    #接收方信息
    message['To'] = receivers[0]

    #登录并发送邮件
    smtpObj = smtplib.SMTP()
    #连接到服务器
    smtpObj.connect(mail_host, 25)
    #登录到服务器
    smtpObj.login(mail_user, mail_pass)
    #发送
    smtpObj.sendmail(sender, receivers, message.as_string())
    #退出
    smtpObj.quit()


if __name__ == '__main__':
    receivers = ['xxxxx@qq.com']
    subject = 'SevenTiny通知'
    content = f'这是邮件主体内容!发送时间:{datetime.now()}'
    send_mail_plain(receivers, subject, content)
    print('Sent successfully!')

说明:

我这里采用了配置文件的方式填充账号密码,这样可以避免在项目中硬编码造成泄露风险
如果需要了解配置文件的使用方式,请参考:https://www.cnblogs.com/7tiny/p/16211724.html

我们需要配置如下几个关键参数:

  • 163用户名
    mail_user = "xxxxx@163.com"
  • 密码(部分邮箱为授权码)
    mail_pass = "开通smtp服务时,163邮箱设置弹出的授权码(只会弹出一次,如果忘记重新配置)"
  • 邮件发送方邮箱地址
    sender = "xxxxx@163.com"

然后填写接收邮箱,主题,内容即可(这部分参考代码参数传递即可,非常简单)

【测试】

我们运行脚本,可以看到收到发送成功的日志

python实现基于smtp发送邮件_在线工具

我们打开163邮箱查看已发送邮箱,可以已发送邮箱中有我们刚才发送的邮件

python实现基于smtp发送邮件_在线工具

打开接收方qq邮箱(也可以是其他邮箱)查看是否正确收到邮件

python实现基于smtp发送邮件_在线工具

可以看到我们已经正确收到了刚才发送的邮件!

【总结】

我们已经通过 python smtp 模块借助163邮箱实现简单的邮件发送,如果是自建邮箱服务器,需要自行将163邮箱服务器地址替换成自己邮箱服务器地址:mail_host = 'smtp.163.com'

注意:163服务器作为发送方,每天有50封邮件上限! 如果超出数量会发送失败。

【源码地址】

https://github.com/sevenTiny/CodeArts/blob/master/Python/Mail/email_163.py

  • 作者:7tiny
  • 原文链接:https://www.cnblogs.com/7tiny/p/16212468.html
    更新时间:2022年5月10日09:56:50 ,共 1720 字。