代码:
emailhelper.py
# -*- coding: UTF-8 -*-
import sys
import platform
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# SMTP 服务
mail_host = "smtp.company.com" # 设置服务器
mail_user = "[email protected]" # 用户名
mail_pass = "password" # 口令
def send_mail( receivers, subject, content, filenames=None):
"""
:param sender:string
:param receivers:list[string] # 如果收件人为多个格式['[email protected]','[email protected]']
subject:string
content: string
filename: string
:return:
"""
sender=mail_user
filenames = [] if filenames is None else filenames #附件名称
try:
message = MIMEMultipart()
message.attach(MIMEText(content, 'plain', 'utf-8'))
message['Subject'] = Header(subject, 'utf-8')
# message['to']格式为:[email protected], [email protected]
message['to'] = ','.join(receivers)
# 如果附件名称大于0个字符
for filename in filenames:
if filename is not None and len(filename.strip()) > 0:
att1 = MIMEText(open(filename, 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = 'attachment; filename="%s" filename
message.attach(att1)
smtp_obj = smtplib.SMTP()
smtp_obj.connect(mail_host, 25) # 25 为 SMTP 端口号
smtp_obj.login(mail_user, mail_pass)
smtp_obj.sendmail(sender, receivers, message.as_string())
smtp_obj.quit()
print "邮件发送成功"
except smtplib.SMTPException, e:
print "Error: 无法发送邮件,code:%s" % e.smtp_code
return
—over—
近期评论