1、简单介绍
在日常的工作中,经常遇到一些例行化的任务,而且还需要监控健康情况,这时可以选择自动发邮件的方式。正好最近使用,就是总结一下:
2、python3 实现
# =============================================================
# !/usr/bin/python
# -*- coding=utf-8 -*-
# Name: email
# Description: Python3发送邮件的简单示例
# Author:
# Date: 2020/4/18
# Mail:
# =============================================================
import smtplib
from email.utils import formatdate
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
username = "user_name" # 发件人用户名
from_addr = username + "@foxmail.com" # 发件人邮箱
password = "12345678" # 自己的密码
smtp_addr = "xx.xx.com" # 服务器地址
# 接收邮件,可设置多个,如果多个用list(和Python2有区别)
to_addrs = ['xxxx1@foxmail.com', 'xxxx2@foxmail.com', 'xxxx3@foxmail.com']
def message_template1(): # 创建邮件内容-模板1
# --------------------邮箱信息内容--------------------------
mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="http://www.jd.com">这是jd链接</a></p>
"""
message = MIMEText(mail_msg, 'html', 'utf-8')
message['Subject'] = Header('Python SMTP 邮件测试', 'utf-8') # 类似于标题
message['From'] = Header(username, 'utf-8') # 邮件,发件人位置显示内容
message['To'] = Header('; '.join(to_addrs), 'utf-8') # 邮件,收件人位置显示的内容
message['Date'] = formatdate(localtime=True)
return message
def message_template2(): # 创建邮件内容-模板2
# --------------------邮箱信息内容--------------------------
mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="http://www.jd.com">这是jd链接</a></p>
"""
message = MIMEMultipart('alternative')
text_html = MIMEText(mail_msg, 'html', 'utf-8')
message['To'] = ';'.join(to_addrs)
message['Date'] = formatdate(localtime=True)
message['Subject'] = 'Python SMTP 邮件测试'
message.add_header('reply-to', from_addr) # 如果需要,做回复的人的邮箱
message.add_header('from', username + "<" + from_addr + ">") # 设置发件人位置的格式
message.attach(text_html)
return message
def send_email_():
message = message_template1()
message = message_template2()
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(host=smtp_addr)
smtpObj.login(username, password)
smtpObj.sendmail(from_addr, to_addrs, message.as_string())
smtpObj.quit()
print("邮件发送成功")
except smtplib.SMTPException as e:
print(repr(e))
print("Error: 无法发送邮件")
if __name__ == '__main__':
send_email_()
声明: 总结学习,有问题或不当之处,可以批评指正哦,谢谢。