欢迎访问宙启技术站
智能推送

如何在Python中发送电子邮件

发布时间:2024-01-12 18:24:13

在Python中发送电子邮件,需要使用smtplib模块来建立SMTP服务器连接,并使用email模块组织和构造邮件内容。下面是一个示例,演示如何使用Python发送电子邮件。

首先,我们需要导入相应的模块:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

然后,我们需要设置SMTP服务器的相关信息:

smtp_server = 'smtp.xxx.com'
smtp_port = 25
username = 'your_email@example.com'
password = 'your_password'
sender = 'your_email@example.com'
receiver = ['receiver_email@example.com']

接下来,我们可以使用MIMEText类来构造纯文本邮件内容,或使用MIMEMultipart类来构造带附件的邮件内容:

subject = 'Python email test'
message = 'This is a test email sent from Python.'

# 构造纯文本邮件
msg = MIMEText(message, 'plain', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = sender
msg['To'] = ','.join(receiver)

# 构造带附件的邮件
msg = MIMEMultipart()
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = sender
msg['To'] = ','.join(receiver)

# 添加邮件正文
msg.attach(MIMEText(message, 'plain', 'utf-8'))

# 添加附件
attachment = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')
attachment['Content-Type'] = 'application/octet-stream'
attachment['Content-Disposition'] = 'attachment; filename="test.txt"'
msg.attach(attachment)

接着,我们可以使用smtplib模块来建立SMTP连接并发送邮件:

try:
    smtp_obj = smtplib.SMTP(smtp_server, smtp_port)
    smtp_obj.login(username, password)
    smtp_obj.sendmail(sender, receiver, msg.as_string())
    print('Email sent successfully!')
except smtplib.SMTPException as e:
    print('Failed to send email!', str(e))
finally:
    smtp_obj.quit()

以上就是使用Python发送电子邮件的主要步骤和代码示例。需要注意的是,这只是一个简单的示例,实际应用中可能还需要处理更多的异常情况,并根据具体需求添加更多的邮件内容和附件。

另外,为了成功发送邮件,需要确保SMTP服务器的设置和账户信息正确,并且网络连接正常。