批量发送邮件

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


smtp_server = "example.test.com"
port = 587# For starttls (consider using 587)
sender_email = "example@test.com"
password = "xxx"
# WARNING: SSL verification is being DISABLED below.
# This is INSECURE and should only be used for local testing.
context = ssl._create_unverified_context()
print("WARNING: SSL certificate verification is DISABLED (INSECURE).")
try:
   server = smtplib.SMTP(smtp_server, port)
   server.ehlo() # 可以省略
   # Start TLS using an unverified (insecure) context
   server.starttls(context=context) # INSECURE: certificate not verified
   server.ehlo() # 可以省略
   server.login(sender_email, password)
   print("登录成功")
   
   # Create the email message
   message = MIMEMultipart("alternative")
   message["Subject"] = "测试主题"
   message["From"] = sender_email
   # message["To"] = "example@test.com"
   text = "test"
   html = """
   <html>
   <body>
      <p>test<br>
         test!
      </p>
   </body>
   </html>
   """
   part1 = MIMEText(text, "plain")
   part2 = MIMEText(html, "html")
   message.attach(part1)
   message.attach(part2)
   
   # Send the email to multiple recipients with a small delay
   recipients = ["example@test.com", "example@test.com"]
   for recipient in recipients:
      message["To"] = recipient
      try:
         server.sendmail(sender_email, recipient, message.as_string())
         print(f"邮件已发送至: {recipient}")
         time.sleep(2) # 适当的时间间隔
      except Exception as e:
         print(f"发送邮件到 {recipient} 时出错: {e}")
except Exception as e:
   print(f"错误: {e}")
finally:
   # 仅在连接仍然存在时调用 quit()
   try:
      if 'server' in locals() and getattr(server, 'sock', None):
         server.quit()
   except Exception:
      pass

发送附件邮件

from email.mime.base import MIMEBase
from email import encoders
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = "receiver@example.com"
message["Subject"] = "带附件的邮件"
body = "这是一个带附件的邮件"
message.attach(MIMEText(body, "plain"))
filename = "document.pdf"
with open(filename, "rb") as attachment:
   part = MIMEBase("application", "octet-stream")
   part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header(
   "Content-Disposition",
   f"attachment; filename= {filename}",
)
message.attach(part)

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐