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

如何使用Python发送带有多个收件人的电子邮件

发布时间:2024-01-12 18:34:16

使用Python发送带有多个收件人的电子邮件可以通过使用smtplib库和email库来实现。以下是一个使用例子:

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

# 设置发件人邮箱和密码
sender_email = 'your_email@gmail.com'
password = 'your_password'

# 创建一个MIMEMultipart对象作为邮件容器
msg = MIMEMultipart()

# 设置邮件内容
msg['From'] = Header('发件人姓名', 'utf-8')
msg['Subject'] = Header('邮件主题', 'utf-8')

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

# 设置收件人邮箱列表
recipient_emails = ['recipient1@example.com', 'recipient2@example.com', 'recipient3@example.com']

# 发送邮件给每个收件人
for recipient_email in recipient_emails:
    # 添加收件人信息
    msg['To'] = Header(recipient_email, 'utf-8')
    
    try:
        # 连接到SMTP服务器
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(sender_email, password)
        
        # 发送邮件
        server.sendmail(sender_email, recipient_email, msg.as_string())
        print(f'邮件成功发送给 {recipient_email}')
        
        # 关闭连接
        server.quit()
    except Exception as e:
        print(f'邮件发送失败给 {recipient_email}: {str(e)}')

上述代码中,我们首先导入了需要的模块,然后设置发件人的邮箱和密码。接下来,我们创建一个MIMEMultipart对象作为邮件容器,并设置邮件的发件人姓名和主题。然后,我们添加了邮件的正文内容。

接下来,我们设置了收件人的邮箱列表,使用一个循环来发送邮件给每个收件人。在循环体内部,我们首先设置了邮件的收件人信息,然后连接到SMTP服务器,并使用登录信息进行登录。然后,我们调用sendmail方法来发送邮件,并输出发送成功的消息。最后,我们关闭了与SMTP服务器的连接。

请注意,上述例子中使用的是Gmail的SMTP服务器信息,请根据你所使用的邮箱提供商的要求进行相应的更改。

希望上述例子能帮助你使用Python发送带有多个收件人的电子邮件。