python发送邮件小demo

这篇博客介绍了如何使用Python进行邮件发送,特别强调了解决中文文件名问题以及设置收件人和发件人名称的方法。
摘要由CSDN通过智能技术生成

工作中涉及使用 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值