用python代码写一个批量发送邮件
时间: 2023-09-12 08:10:34 浏览: 190
以下是一个简单的Python代码示例,可以用于批量发送邮件。请注意,在使用此代码之前,您需要将其中的发件人电子邮件地址和密码替换为您自己的。
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 设置发件人和收件人
sender_email = 'your_email@example.com'
sender_password = 'your_email_password'
recipient_emails = ['recipient1@example.com', 'recipient2@example.com']
# 创建邮件消息
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = ', '.join(recipient_emails)
message['Subject'] = 'Test email'
# 添加邮件正文
text = 'This is a test email sent using Python'
message.attach(MIMEText(text))
# 发送邮件
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(sender_email, sender_password)
smtp.send_message(message)
print('Email sent successfully.')
```
如果您想要批量发送邮件,可以将上述代码放入循环中,并在每次迭代中更改收件人电子邮件地址。例如:
```python
for recipient in recipient_emails:
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = recipient
message['Subject'] = 'Test email'
text = 'This is a test email sent using Python'
message.attach(MIMEText(text))
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(sender_email, sender_password)
smtp.send_message(message)
print(f'Email sent to {recipient} successfully.')
```
请注意,这是一个简单的示例代码,可能需要根据您的具体需求进行修改。例如,您可能需要添加附件或使用不同的邮件服务器。
阅读全文