python smtplib发送邮件可直接运行代码
Posted bitcarmanlee
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python smtplib发送邮件可直接运行代码相关的知识,希望对你有一定的参考价值。
0 说明
以下代码,只需根据个人情况修改相应配置即可直接运行。
1.发送普通格式邮件
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import logging
def send_html():
token = 'xxx'
receivers = ['xxx@xxx.com']
mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="https://www.baidu.com/">这是百度的链接</a></p>
"""
message = MIMEText(mail_msg, 'html', 'utf-8')
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP()
smtpObj.connect("xxx")
smtpObj.sendmail(token, receivers, message.as_string())
print("邮件发送成功")
except smtplib.SMTPException as e:
print("Error: 无法发送邮件")
logging.exception(e)
send_html()
2.发送带附件邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
def send_mail():
token = 'xxx'
receivers = ['xxx@xxx.com'] # 接收邮件
# 创建一个带附件的实例
message = MIMEMultipart()
subject = 'Python SMTP 发送添加附件的邮件'
message['Subject'] = Header(subject, 'utf-8')
message.attach(MIMEText('这是Python 邮件发送测试……', 'plain', 'utf-8'))
# 构造附件,传送当前目录下的文件
att = MIMEText(open('pltimage.py', 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att["Content-Disposition"] = 'attachment; filename="pltimage.txt"'
message.attach(att)
try:
smtpObj = smtplib.SMTP()
smtpObj.connect("xxx")
smtpObj.sendmail(token, receivers, message.as_string())
print("邮件发送成功")
except smtplib.SMTPException:
print("Error: 无法发送邮件")
send_mail()
3.
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
import logging
def send_mail():
token = 'xxx'
receivers = ['xxx@xxx.com'] # 接收邮件
msgRoot = MIMEMultipart('related')
subject = 'Python SMTP 发送图片邮件测试'
msgRoot['Subject'] = Header(subject, 'utf-8')
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
mail_msg = """
<p>这是一张手机桌面的截图...</p>
<p>图片演示:</p>
<p><img src="cid:image1"></p>
"""
msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))
# 指定图片为当前目录
fp = open('images/img1.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# 定义图片 ID,在 HTML 文本中引用
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
try:
smtpObj = smtplib.SMTP()
smtpObj.connect("xxx")
smtpObj.sendmail(token, receivers, msgRoot.as_string())
print("邮件发送成功")
except smtplib.SMTPException as ex:
logging.exception(ex)
print("Error: 无法发送邮件")
send_mail()
以上是关于python smtplib发送邮件可直接运行代码的主要内容,如果未能解决你的问题,请参考以下文章
编写python的smtplib库发送邮件代码(简洁-原创)