Python下的邮件发送示例
Exchange邮箱发送示例
注:邮件内容是使用HTML构建的,如果熟悉这方面,可以使用HTML的方式构建自己想要的内容结构
安装包:
pip install exchangelib
导包
from exchangelib import Credentials, Account, DELEGATE, Configuration, NTLM, Message, Mailbox, HTMLBody
from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter
import urllib3
from exchangelib import Credentials, Account, DELEGATE, Configuration, NTLM, Message, Mailbox, HTMLBody
from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter
import urllib3
urllib3.disable_warnings() # 取消SSL安全连接警告
BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter
cred = Credentials('域/用户名', '密码') # 用户名不需要填写后缀
config = Configuration(
server='邮箱服务器', # 例如:mail.****.com
credentials=cred,
auth_type=NTLM
)
account = Account(
primary_smtp_address='发件人邮箱地址', # 例如:ad@test.com
config=config,
autodiscover=False,
access_type=DELEGATE
)
def Email(to, subject, body): # 创建函数用于方便调用发送
m = Message(
account=account,
subject=subject,
body=HTMLBody(body),
to_recipients=[Mailbox(email_address=to)]
)
m.send()
Email("XXXX@qq.com", "邮件标题", "测试邮件内容") # 测试调用发送邮件
QQ邮箱发送示例
QQ邮箱需要获取“授权码”,在登录密码处填写授权码即可
示例1:
import smtplib
import email.utils
from email.mime.text import MIMEText
message = MIMEText("我是邮件的内容")
message['To'] = email.utils.formataddr(('接收者显示的姓名', '接受邮箱地址'))
message['From'] = email.utils.formataddr(('发送者显示的姓名', '发送邮箱地址'))
message['Subject'] = '我是邮件的标题'
server = smtplib.SMTP_SSL('smtp.qq.com', 465)
#开始登录,第一个参数为登录邮箱地址
server.login('发送登录邮箱地址','密码')
server.set_debuglevel(True)
try:
server.sendmail('发件人邮箱',['收件人邮箱'],msg=message.as_string())
finally:
server.quit()
示例2:
import smtplib
import time
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
# 邮件收件人发件人设置
host_server = 'smtp.qq.com' # qq邮箱smtp服务器
sender_qq = 'xxxx@qq.com' # 发件人邮箱
pwd = '授权码'
receiver = "收件人邮箱"
mail_title = "资讯概况" # 邮件标题
# 邮件正文内容
title = "<p>小主,早上好,以下是热榜内容</p>"
p1 = "------百度前30条搜索热榜------"
p2 = "------知乎前50条搜索热榜------"
mail_content = title + p1 +p2
msg = MIMEMultipart('alternative')
msg["Subject"] = Header(mail_title, 'utf-8')
msg["From"] = sender_qq
msg["To"] = Header(receiver, "utf-8")
msg.attach(MIMEText(mail_content, 'html'))
try:
smtp = SMTP_SSL(host_server) # ssl登录连接到邮件服务器
smtp.set_debuglevel(0) # 0是关闭,1是开启debug
smtp.ehlo(host_server) # 跟服务器打招呼,告诉它我们准备连接,最好加上这行代码
smtp.login(sender_qq, pwd)
smtp.sendmail(sender_qq, receiver, msg.as_string())
smtp.quit()
print("邮件发送成功")
except smtplib.SMTPException:
print("无法发送邮件")