实现
在Python环境下,通过使用mtplib和email包发送邮件。
from email.message import Message
import smtplib
import traceback
def sendEmail(sender, password, receiver, sendInfoList):
string_list = sendInfoList
if string_list != []:
email_context = '邮件信息:</p><br>'
for string_list_item in string_list:
email_context+=(string_list_item+'</p><br>')
html_content_before = '''
<html>
<body>'''
html_content_after = '''
</body>
</html>
'''
html_content = html_content_before + email_context + html_content_after
msg = Message()
# 邮件标题
msg['Subject'] = '这里是邮件标题,请查看!'
# 邮件发送者
msg['From'] = sender
# 邮件接受者
msg['To'] = receiver
# 邮件内容格式
msg.set_type('text/html')
# 邮件内容
msg.set_payload(html_content, 'utf-8')
try:
smtp = smtplib.SMTP_SSL('smtp.163.com', 465)#163/126/qq...端口根据服务商要求设置
smtp.login(sender, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
print('邮件发送成功!')
return 'OK'
except smtplib.SMTPException:
traceback.print_exc()
print('邮件发送失败!')
return 'NO'
else:
return 'NO'
if __name__ == '__main__':
sendInfoList = ['test','hello','world']#需发送的信息
sender = 'sender_name@163.com'#邮箱用户名
password = 'password'#邮箱密码
receiver = 'receiver_name@qq.com'#接收邮箱,可以为list,但需将msg['To'] = receiver改为msg['To'] = ', '.join(receiver)
watch_flag = sendEmail(sender, password, receiver, sendInfoList)
print(watch_flag)