在服务器上发送邮件,通常需要使用SMTP(Simple Mail Transfer Protocol)协议,Python的smtplib库提供了这个功能,以下是一个简单的例子,它将发送一封电子邮件。

(图片来源网络,侵删)
解析:
1、导入smtplib和MIMEText模块。
2、设置SMTP服务器地址和端口。
3、创建SMTP对象并连接到服务器。
4、登录到SMTP服务器。
5、创建邮件对象,设置发件人、收件人和邮件主题。
6、添加邮件正文。
7、发送邮件。

(图片来源网络,侵删)
8、关闭SMTP连接。
代码如下:
import smtplib from email.mime.text import MIMEText SMTP服务器地址和端口 smtp_server = 'smtp.example.com' smtp_port = 587 创建SMTP对象并连接到服务器 server = smtplib.SMTP(smtp_server, smtp_port) 登录到SMTP服务器 server.login('your_email@example.com', 'your_password') 创建邮件对象,设置发件人、收件人和邮件主题 msg = MIMEText('This is the body of the email.') msg['From'] = 'your_email@example.com' msg['To'] = 'recipient@example.com' msg['Subject'] = 'Hello there!' 发送邮件 server.sendmail('your_email@example.com', 'recipient@example.com', msg.as_string()) 关闭SMTP连接 server.quit()
注意:这个例子中的’your_email@example.com’和’your_password’应该被替换为你的邮箱地址和密码,同样,’recipient@example.com’应该被替换为你想要发送邮件的人的邮箱地址。

(图片来源网络,侵删)
【版权声明】:本站所有内容均来自网络,若无意侵犯到您的权利,请及时与我们联系将尽快删除相关内容!
发表回复