工作中涉及使用 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