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 协议》,转载必须注明作者和本文链接
雪花飘
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 2

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

6年前 评论

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