经过大量的搜索,我无法找到如何使用smtplib。发送邮件到多个收件人。问题是每次发送邮件时,邮件标题似乎包含多个地址,但实际上只有第一个收件人会收到电子邮件。
问题似乎出在邮件上。Message模块期望与smtplb .sendmail()函数不同的内容。
简而言之,要发送给多个收件人,您应该将标题设置为一串以逗号分隔的电子邮件地址。sendmail()参数to_addr应该是一个电子邮件地址列表。
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import smtplib
msg = MIMEMultipart()
msg["Subject"] = "Example"
msg["From"] = "me@example.com"
msg["To"] = "malcom@example.com,reynolds@example.com,firefly@example.com"
msg["Cc"] = "serenity@example.com,inara@example.com"
body = MIMEText("example email body")
msg.attach(body)
smtp = smtplib.SMTP("mailhost.example.com", 25)
smtp.sendmail(msg["From"], msg["To"].split(",") + msg["Cc"].split(","), msg.as_string())
smtp.quit()
我提出了这个可导入模块函数。本例中使用的邮件服务器为gmail。它分为头和消息,所以你可以清楚地看到发生了什么:
import smtplib
def send_alert(subject=""):
to = ['email@one.com', 'email2@another_email.com', 'a3rd@email.com']
gmail_user = 'me@gmail.com'
gmail_pwd = 'my_pass'
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + ", ".join(to) + '\n' + 'From: ' + gmail_user + '\n' + 'Subject: ' + subject + '\n'
msg = header + '\n' + subject + '\n\n'
smtpserver.sendmail(gmail_user, to, msg)
smtpserver.close()
您可以在将收件人电子邮件写入文本文件时尝试此操作
from email.mime.text import MIMEText
from email.header import Header
import smtplib
f = open('emails.txt', 'r').readlines()
for n in f:
emails = n.rstrip()
server = smtplib.SMTP('smtp.uk.xensource.com')
server.ehlo()
server.starttls()
body = "Test Email"
subject = "Test"
from = "me@example.com"
to = emails
msg = MIMEText(body,'plain','utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = Header(from, 'utf-8')
msg['To'] = Header(to, 'utf-8')
text = msg.as_string()
try:
server.send(from, emails, text)
print('Message Sent Succesfully')
except:
print('There Was An Error While Sending The Message')
这里有很多答案在技术上或部分上是正确的。在阅读了每个人的答案后,我想出了这个更可靠/通用的电子邮件功能。我已经确认它的工作,你可以通过HTML或纯文本的主体。注意,此代码不包括附件代码:
import smtplib
import socket
# Import the email modules we'll need
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
#
# @param [String] email_list
# @param [String] subject_line
# @param [String] error_message
def sendEmailAlert(email_list="default@email.com", subject_line="Default Subject", error_message="Default Error Message"):
hostname = socket.gethostname()
# Create message
msg = MIMEMultipart()
msg['Subject'] = subject_line
msg['From'] = f'no-reply@{hostname}'
msg['To'] = email_list
msg.attach(MIMEText(error_message, 'html'))
# Send the message via SMTP server
s = smtplib.SMTP('localhost') # Change for remote mail server!
# Verbose debugging
s.set_debuglevel(2)
try:
s.sendmail(msg['From'], msg['To'].split(","), msg.as_string())
except Exception as e:
print(f'EMAIL ISSUE: {e}')
s.quit()
这显然可以修改为使用本机Python日志记录。我只是提供了一个坚实的核心功能。我也不能强调这一点,sendmail()需要一个列表,而不是一个字符串!函数适用于Python3.6+