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

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

发布时间:2024-01-16 04:08:50

使用smtplib发送带有多个收件人的电子邮件可以通过以下步骤实现:

1. 导入所需的模块:

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

2. 设置发送方和收件人信息:

sender = 'your_email@gmail.com'
receivers = ['receiver1@gmail.com', 'receiver2@gmail.com', 'receiver3@gmail.com']

3. 创建一个包含邮件主体的MIMEMultipart实例:

message = MIMEMultipart()
message['From'] = sender
message['To'] = ', '.join(receivers)  # 将收件人列表转为逗号分隔的字符串
message['Subject'] = 'Subject of the Email'

4. 添加邮件内容:

body = """
This is the body of the email.
You can write your message here.
"""
message.attach(MIMEText(body, 'plain'))

5. 构建smtp服务器,并登录发送方邮箱:

smtp_server = smtplib.SMTP('smtp.gmail.com', 587)
smtp_server.starttls()
smtp_server.login(sender, 'your_password')

注意:在使用Gmail发送邮件时,需要开启SMTP和IMAP协议,并使用应用专用密码。

6. 发送邮件:

smtp_server.send_message(message)

7. 关闭smtp服务器:

smtp_server.quit()

完整的示例代码如下:

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

sender = 'your_email@gmail.com'
receivers = ['receiver1@gmail.com', 'receiver2@gmail.com', 'receiver3@gmail.com']

message = MIMEMultipart()
message['From'] = sender
message['To'] = ', '.join(receivers)
message['Subject'] = 'Subject of the Email'

body = """
This is the body of the email.
You can write your message here.
"""
message.attach(MIMEText(body, 'plain'))

smtp_server = smtplib.SMTP('smtp.gmail.com', 587)
smtp_server.starttls()
smtp_server.login(sender, 'your_password')

smtp_server.send_message(message)

smtp_server.quit()

使用以上代码,你可以发送带有多个收件人的电子邮件。只需将你的邮箱和密码替换为合适的值,并修改收件人的邮箱地址即可。