Python中使用smtplib发送给多个收件人可以通过以下步骤实现:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()
msg['From'] = 'sender@example.com'
msg['To'] = ', '.join(['recipient1@example.com', 'recipient2@example.com'])
msg['Subject'] = '邮件主题'
body = '邮件正文内容'
msg.attach(MIMEText(body, 'plain'))
attachment = MIMEText(open('attachment.txt', 'rb').read(), 'base64', 'utf-8')
attachment['Content-Type'] = 'application/octet-stream'
attachment['Content-Disposition'] = 'attachment; filename="attachment.txt"'
msg.attach(attachment)
smtp_server = 'smtp.example.com'
smtp_port = 25
username = 'your_username'
password = 'your_password'
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.login(username, password)
server.sendmail(msg['From'], msg['To'].split(', '), msg.as_string())
以上代码示例了如何使用Python的smtplib库发送给多个收件人的邮件。其中,smtplib用于连接SMTP服务器并发送邮件,email模块用于创建邮件对象和设置邮件内容。通过MIMEMultipart对象可以设置邮件的发送者、收件人、主题等信息,并可以添加邮件正文和附件。
推荐的腾讯云相关产品:腾讯云邮件推送(https://cloud.tencent.com/product/ses)是腾讯云提供的邮件推送服务,可以方便地通过API接口发送邮件。
领取专属 10元无门槛券
手把手带您无忧上云