08 – Python SMTP发送邮件

  • Post author:
  • Post category:python


SMTP Send Email

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib

smtp_server = 'SMTP Server'
receivers = 'a@email.com,b@email.com'
cc = 'c@email.com,d@email.com'
sender = 'Someone to Send Email'
subject = 'This is Email Subject'
body = 'This is Email Body'
template_dir = 'c:/Folder'
files = ['file1.txt','file2.csv']

# 创建一个带附件的实例
msg = MIMEMultipart()
msg.attach(MIMEText(body, 'plain', 'utf-8'))
for file_name in files:
    att = MIMEText(open(template_dir + '/' + file_name, 'rb').read(), 'base64', 'gb2312')
    att["Content-Type"] = 'application/octet-stream'
    att["Content-Disposition"] = 'attachment; filename="{}"'.format(file_name)  # 这里的filename可以任意写,写什么名字,邮件中显示什么名字
    msg.attach(att)

# 邮件主要信息
msg['to'] = receivers
msg['from'] = sender
msg['subject'] = subject
to_addr = msg['to'].split(',')

if cc is not None:
    msg['cc'] = cc
    to_addr += msg['cc'].split(',')
    
# 发送邮件
server = smtplib.SMTP(smtp_server)
server.ehlo()   # 向邮箱发送SMTP ehlo 命令
server.starttls()
server.sendmail(msg['from'], to_addr, msg.as_string())
server.quit()



版权声明:本文为qq_41711469原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。