如何使用python发邮件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def send_email(sender_email, sender_password, recipient_email, subject, body): # 设置 SMTP 服务器的地址和端口号 smtp_server = 'smtp.126.com' smtp_port = 465 # SSL连接一般使用465端口 # 创建一个 SSL 连接 server = smtplib.SMTP_SSL(smtp_server, smtp_port) # 登录到你的邮箱账号 server.login(sender_email, sender_password) # 创建一个邮件对象 msg = MIMEMultipart() msg[ 'From' ] = sender_email msg[ 'To' ] = recipient_email msg[ 'Subject' ] = subject # 添加邮件正文 msg.attach(MIMEText(body, 'plain' )) try : # 发送邮件 server.send_message(msg) print ( "邮件发送成功!" ) except Exception as e: print ( "邮件发送失败:" , str (e)) finally : # 关闭连接 server.quit() # 使用时调用该函数 send_email( 'xxxxxxxxxxxx@126.com' , ' ', ' xxxxxxxxxx@qq.com ', ' Test Subject ', ' Hello, this is a test email!') |
-
sender_email
: 发件人的电子邮件地址。这是你想要通过该函数发送邮件的邮箱地址。 -
sender_password
: 发件人邮箱的密码。为了通过邮件服务器进行身份验证,需要提供发件人邮箱的密码。 -
recipient_email
: 收件人的电子邮件地址。这是你想要发送邮件的目标邮箱地址。 -
subject
: 邮件的主题。这是邮件的标题,用来简要描述邮件的内容。 -
body
: 邮件的正文内容。这是你想要在邮件中传达的消息,可以是文本、HTML或者其他格式。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库