Python 的邮件发送
Python的邮件发送
-
发送邮件传输协议(SMTP)用作使用python处理电子邮件传输的协议。它用于在电子邮件服务器之间路由电子邮件。
-
Python提供了smtplib模块,该模块定义了一个SMTP客户端会话对象,用于将电子邮件发送到Internet机器。为此,我们必须使用import语句导入smtplib模块。
import smtplib
- SMTP对象用于电子邮件传输。以下语法用于创建smtplib对象。
import smtplib
smtp = smtplib.SMTP(host, port, local_hostname)
- 参数解释
- host:它是运行SMTP服务器的计算机的主机名。在这里,我们可以指定服务器的IP地址,如(https://www.javatpoint.com)或 localhost。这是一个可选参数。
- port:主机正在侦听SMTP连接的端口号。默认为25。
- local_hostname:如果SMTP服务器在本地计算机上运行,我们可以提及本地计算机的主机名。
- sendmail()方法用于SMTP对象发送邮件到接受者的电子邮箱,语法如下:
smtp.sendmail(sender, receiver, message)
- 示例
import smtplib
sender_mail = 'sender@fromdomain.com'
receivers_mail = 'reciever@todomain.com'
message = """From: From Person %s
To: To Person %s
Subject: Sending SMTP e-mail
This is a test e-mail message.
"""%(sender_mail, receivers_mail)
try:
smtp = smtplib.SMTP('localhost')
smtp.sendmail(sender_mail, receivers_mail, message)
print("Successfully sent email")
except Exception:
print("Error: unable to send email")
- 从gmail发送电子邮件
- 有些情况下使用gmail SMTP服务器发送电子邮件。在这种情况下,我们可以将gmail作为SMTP服务器传递,而不是将localhost与端口587一起使用
- 使用以下语法:
smtp = smtplib.SMTP('gmail.com', 587)
- 我们需要使用 gmail 用户名和密码登录 gmail 帐户。为此,smtplib提供了login()方法,该方法接受发件人的用户名和密码
-示例
import smtplib
sender_mail = 'sender@gmail.com'
receivers_mail = 'reciever@gmail.com'
message = """From: From Person %s
To: To Person %s
Subject: Sending SMTP e-mail
This is a test e-mail message.
"""%(sender_mail,receivers_mail)
try:
password = input('Enter the password');
smtp = smtplib.SMTP('gmail.com',587)
smtp.login(sender_mail, password)
smtp.sendmail(sender_mail, receivers_mail, message)
print("Successfully sent email")
except Exception:
print("Error: unable to send email")
- 在电子邮件中发送 HTML
- 我们可以通过指定要发送HTML的MIME版本,内容类型和字符集来格式化消息中的HTML
- 示例
import smtplib
sender_mail = 'sender@fromdomain.com'
receivers_mail = ['reciever@todomain.com']
message = """From: From Person %s
To: To Person %s
MIME-Version:1.0
Content-type:text/html
Subject: Sending SMTP e-mail
<h3>Python SMTP</h3>
<strong>This is a test e-mail message.</strong>
"""%(sender_mail,receivers_mail)
try:
smtp = smtplib.SMTP('localhost')
smtp.sendmail(sender_mail, receivers_mail, message)
print("Successfully sent email")
except Exception:
print("Error: unable to send email")
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 2025成都.NET开发者Connect圆满结束
· 后端思维之高并发处理方案
· 千万级大表的优化技巧
· 在 VS Code 中,一键安装 MCP Server!
· 10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析