python 发送邮件 demo

工作中涉及使用 python 发送邮件,代码如下

from conf.Config import Config
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.utils import formataddr
import sys

def send(users, subject, title, attach_path=None,attach_name=None):

    temp = users.split(',')
    receivers = []
    for item in temp:
        if item.find('@') == -1:
            receivers.append(item+'@xx.com')
        else:
            receivers.append(item)
    #连接配置
    conf = Config().email_config()
    from_name = conf['name']
    message = MIMEMultipart()
    message['From'] = formataddr(['xxx', from_name])
    message['To'] = formataddr([users, ','.join(receivers)])
    message['Subject'] = subject

    message.attach(MIMEText(title, 'plain', 'utf-8'))
    if attach_path and attach_name:
        attach = MIMEText(open(attach_path, 'rb').read(), 'base64', 'utf-8')
        attach['Content-Type'] = 'application/octet-stream'
        attach.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', attach_name))
        message.attach(attach)

    try:
        smtpObj = smtplib.SMTP_SSL(conf['host'], conf['port'])
        smtpObj.login(conf['name'], conf['pwd'])
        smtpObj.sendmail(conf['name'], receivers, message.as_string())
        print("邮件发送成功...")
    except smtplib.SMTPException as e:
        print("Error:无法发送邮件",e)

if __name__ == '__main__':
    receivers = sys.argv[1]
    subject = sys.argv[2]
    title = sys.argv[3]
    attach_path = sys.argv[4]
    attach_name = sys.argv[5]
    send(receivers, subject, title, attach_path, attach_name)

其中注意:

  • attach.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', attach_name)) 解决中文文件名问题 ;
  • smtpObj.sendmail(conf['name'], receivers, message.as_string()) 这里 receivers 收件人列表对应message['To'] = formataddr([users, ','.join(receivers)]) 这里的收件人 ','.join(receivers)
  • smtpObj.sendmail(conf['name'], receivers, message.as_string()) 这里的 conf['name'] 对应 message['From'] = formataddr(['xxx', from_name]) 这里的 from_name
本作品采用《CC 协议》,转载必须注明作者和本文链接
雪花飘
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 2

@邪恶的咖啡 纯笔记分享,不必纠结这个

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!