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

Python中利用smtplib库实现批量发送邮件的方法

发布时间:2023-12-25 13:24:49

Python提供了smtplib库来实现发送邮件的功能,在使用该库发送邮件之前,需要先连接到SMTP服务器。SMTP(Simple Mail Transfer Protocol)是用于电子邮件传输的协议。

下面是使用smtplib库实现批量发送邮件的方法:

1. 导入smtplib库和MIMEText类

import smtplib
from email.mime.text import MIMEText

2. 设置SMTP服务器地址、端口和登录信息

smtp_server = 'smtp.example.com'  # SMTP服务器地址
smtp_port = 587  # SMTP服务器端口
smtp_username = 'your_username'  # SMTP服务器登录用户名
smtp_password = 'your_password'  # SMTP服务器登录密码

3. 创建MIMEText对象,设置邮件内容和类型

msg = MIMEText('This is the content of the email', 'plain')  # 邮件内容和类型
msg['Subject'] = 'Subject of the email'  # 邮件主题
msg['From'] = 'from@example.com'  # 发件人邮箱
msg['To'] = 'to@example.com'  # 收件人邮箱

4. 连接SMTP服务器并登录账号

server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()  # 启用TLS加密
server.login(smtp_username, smtp_password)

5. 批量发送邮件

email_list = ['recipient1@example.com', 'recipient2@example.com', 'recipient3@example.com']
for recipient in email_list:
    msg['To'] = recipient
    server.sendmail(smtp_username, recipient, msg.as_string())

6. 关闭SMTP连接

server.quit()

下面是一个完整的使用例子:

import smtplib
from email.mime.text import MIMEText

smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'your_username'
smtp_password = 'your_password'

msg = MIMEText('This is the content of the email', 'plain')
msg['Subject'] = 'Subject of the email'
msg['From'] = 'from@example.com'
msg['To'] = 'to@example.com'

server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(smtp_username, smtp_password)

email_list = ['recipient1@example.com', 'recipient2@example.com', 'recipient3@example.com']
for recipient in email_list:
    msg['To'] = recipient
    server.sendmail(smtp_username, recipient, msg.as_string())

server.quit()

以上就是使用smtplib库实现批量发送邮件的方法,可以根据实际需求进行修改和扩展。