注:邮件内容是使用HTML构建的,如果熟悉这方面,可以使用HTML的方式构建自己想要的内容结构
安装包:
pip install exchangelib
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邮箱需要获取“授权码”,在登录密码处填写授权码即可
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()
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("无法发送邮件")
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有