使用python原生的方法实现发送email

使用python原生的方法实现发送email


import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.utils import COMMASPACE
from email import encoders
import os # 发送账号信息
sender = 'xxxxx@qq.com'
password = 'xxxxxxxxxx' # 授权码
'''
html:内容
subject: 主题
receivers:接收者,类型字符串,例子:xx@xx.xx list
''' def send_email(receivers, subject, html):
print(html)
if not isinstance(receivers, list):
receivers = [receivers]
message = MIMEMultipart()
content_message = MIMEText(html, 'HTML', 'utf-8')
message.attach(content_message)
message['From'] = sender
message['To'] = COMMASPACE.join(receivers)
message['Subject'] = subject
# for file in files:
# part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data
# print(open(file, 'r').read())
# part.set_payload(open(file, 'r').read())
# encoders.encode_base64(part)
# part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
# message.attach(part) smtpObj = smtplib.SMTP_SSL(host='smtp.qq.com')
smtpObj.login(sender, password)
result = smtpObj.sendmail(sender, receivers, message.as_string())
smtpObj.quit()
# send_mail('用户激活', 'hello', settings.SERVER_EMAIL, [email])
return result # Note:
# 内容最好是动态内容,每次不一样,而且不要太频繁
msg = '''
<h1> Hello</h1><a href="http://www.baidu.com">baidu</a>
'''
print(send_email(['xxx@xxx.com', 'xxx@qq.com'], '你好', msg))
上一篇:Python测试函数的方法之一


下一篇:Python中sorted()方法