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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章