法一
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
import smtplib
from template import DATETIME
class Email(object):
def __init__(self, file_path, file_name):
self.subject = "********" # 邮件标题
self.sender = '****@huawei.com' # 发件人
self.receivers = ["*****@huawei.com", "*****@huawei.com", "***@huawei.com", "*****@huawei.com"] # 收件人
self.cc = ['***@huawei.com'] # 抄送人
self.file_path = file_path
self.file_name = file_name # 发送附件名字
def message_init(self, html):
# 创建一个带附件的实例
message = MIMEMultipart() # 发送消息定义
message['Subject'] = Header(self.subject, 'utf-8')
message['From'] = self.sender # 发件人
message['To'] = ', '.join(self.receivers) # 收件人
message['Cc'] = ', '.join(self.cc) # 抄送者
# 解决乱码,html是html格式的str
message_context = MIMEText(html, _subtype='html', _charset='utf-8')
# 邮件正文内容
message.attach(message_context)
att1 = MIMEText(open('{}/{}'.format(self.file_path, self.file_name), 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 附件名称
att1["Content-Disposition"] = 'attachment; filename={}'.format(self.file_name.split('\\')[-1])
message.attach(att1) # 添加附件
return message
def send_email(self, html):
message = self.message_init(html)
smtp_obj = smtplib.SMTP('smtp.huawei.com')
smtp_obj.login('工号', "密码") # 打开电脑的账号密码
smtp_obj.sendmail(self.sender, self.receivers + self.cc, message.as_string())
smtp_obj.quit()
法二
#coding: utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = '邮箱地址'
receiver = '邮箱地址'
username = '工号'
password = '密码'
subject = 'python email test'
#中文需参数‘utf-8’,单字节字符不需要
msg = MIMEText('你好呀,最近好么','plain','utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg["From"] = sender
msg["To"] = str(receiver)
msg["Reply-To"] = sender
smtpserver = 'smtpscn.huawei.com'
server_port = 587
#print email_message
#创建SMTP对象
smtp = smtplib.SMTP(smtpserver,server_port)
#smtp.set_debuglevel(1)
#向mail发送SMTP "ehlo" 命令
smtp.ehlo()
#启动TLS模式,mail要求
smtp.starttls()
#用户验证
smtp.login(username, password)
#发送邮件
smtp.sendmail(sender, receiver, msg.as_string())
#退出
smtp.quit()
优秀参考文档
python自动化发送邮件