Python群发邮件的代码示例与解析
分类:默认分类
浏览:40
2024-10-09
pip install secure-smtplib同时,你还需要一个邮件服务器的SMTP地址和端口。这里以Gmail为例:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # 邮件服务器配置 smtp_server = "smtp.gmail.com" smtp_port = 587 username = "[email protected]" password = "your_password" # 邮件内容 subject = "这是一个测试邮件" body = "你好,这是一封测试邮件。" # 收件人列表 recipients = ["[email protected]", "[email protected]"] # 创建MIMEMultipart对象 msg = MIMEMultipart() msg['From'] = username msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) try: # 连接到SMTP服务器 server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() server.login(username, password) # 逐个发送邮件 for recipient in recipients: msg['To'] = recipient server.sendmail(username, recipient, msg.as_string()) print(f"邮件已发送给: {recipient}") server.quit() print("所有邮件发送完成!") except Exception as e: print(f"发送邮件失败: {e}")