当前位置:首页 > 行业动态 > 正文

python 如何发送email

要使用Python发送电子邮件,可以使用smtplib库和email库,以下是一个简单的示例:

python 如何发送email  第1张

1、确保已经安装了smtplib和email库,如果没有安装,可以使用以下命令安装:

pip install securesmtplib
pip install email

2、编写一个Python脚本来发送电子邮件,以下是一个示例:

python 如何发送email  第2张

import smtplib
from email.mime.text import MIMEText
from email.header import Header
发件人和收件人的邮箱地址
sender = 'your_email@example.com'
receiver = 'receiver_email@example.com'
邮件主题和内容
subject = '邮件主题'
content = '邮件正文'
创建邮件对象
message = MIMEText(content, 'plain', 'utf8')
message['From'] = Header(sender, 'utf8')
message['To'] = Header(receiver, 'utf8')
message['Subject'] = Header(subject, 'utf8')
发送邮件
try:
    smtp_obj = smtplib.SMTP('smtp.example.com', 587)  # 使用你的SMTP服务器地址和端口
    smtp_obj.login('your_email@example.com', 'your_password')  # 使用你的邮箱地址和密码登录
    smtp_obj.sendmail(sender, [receiver], message.as_string())
    print("邮件发送成功")
except smtplib.SMTPException as e:
    print("Error: 无法发送邮件", e)

请将上述代码中的your_email@example.comreceiver_email@example.comsmtp.example.comyour_password替换为实际的发件人邮箱地址、收件人邮箱地址、SMTP服务器地址和发件人邮箱密码。

0