如何使用 python smtplib 向多个收件人发送电子邮件?

发布于 2024-12-26 15:25:31 字数 1782 浏览 14 评论 0原文

经过大量搜索后,我无法找到如何使用 smtplib.sendmail 发送给多个收件人。问题是每次发送邮件时,邮件标头都会显示包含多个地址,但实际上只有第一个收件人会收到电子邮件。

问题似乎是 email.Message模块需要与 smtplib.sendmail() 函数。

简而言之,要发送给多个收件人,您应该将标头设置为一串以逗号分隔的电子邮件地址。然而,sendmail() 参数to_addrs 应该是电子邮件地址列表。

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import smtplib

msg = MIMEMultipart()
msg["Subject"] = "Example"
msg["From"] = "[email protected]"
msg["To"] = "[email protected],[email protected],[email protected]"
msg["Cc"] = "[email protected],[email protected]"
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()

After much searching I couldn't find out how to use smtplib.sendmail to send to multiple recipients. The problem was every time the mail would be sent the mail headers would appear to contain multiple addresses, but in fact only the first recipient would receive the email.

The problem seems to be that the email.Message module expects something different than the smtplib.sendmail() function.

In short, to send to multiple recipients you should set the header to be a string of comma delimited email addresses. The sendmail() parameter to_addrs however should be a list of email addresses.

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import smtplib

msg = MIMEMultipart()
msg["Subject"] = "Example"
msg["From"] = "[email protected]"
msg["To"] = "[email protected],[email protected],[email protected]"
msg["Cc"] = "[email protected],[email protected]"
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()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

影子是时光的心 2025-01-02 15:25:31

确实有效,我花了很多时间尝试多种变体。

import smtplib
from email.mime.text import MIMEText

s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = '[email protected]'
recipients = ['[email protected]', '[email protected]']
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())

This really works, I spent a lot of time trying multiple variants.

import smtplib
from email.mime.text import MIMEText

s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = '[email protected]'
recipients = ['[email protected]', '[email protected]']
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())
沉鱼一梦 2025-01-02 15:25:31

msg['To'] 需要是一个字符串:

msg['To'] = "[email protected], [email protected], [email protected]"

sendmail(sender,recipients, message) 中的 recipients 需要是列表:

sendmail("[email protected]", ["[email protected]", "[email protected]", "[email protected]"], "Howdy")

The msg['To'] needs to be a string:

msg['To'] = "[email protected], [email protected], [email protected]"

While the recipients in sendmail(sender, recipients, message) needs to be a list:

sendmail("[email protected]", ["[email protected]", "[email protected]", "[email protected]"], "Howdy")
穿透光 2025-01-02 15:25:31

您需要了解电子邮件的可见地址和送达之间的区别。

msg["To"] 本质上是信函上打印的内容。实际上并没有任何作用。除了您的电子邮件客户端,就像普通的邮递员一样,会假设这就是您想要将电子邮件发送给的人。

然而,实际的交付可能会完全不同。因此,您可以将电子邮件(或副本)放入完全不同的人的邮箱中。

造成这种情况的原因有多种。例如转发To: 标头字段在转发时不会更改,但电子邮件会被放入不同的邮箱中。

smtp.sendmail 命令现在负责实际传送。 email.Message 只是信件的内容,而不是投递内容。

在低级 SMTP 中,您需要一一给出收件人,这就是为什么地址列表(不包括名称!)是明智的 API。

对于标头,它还可以包含例如名称,例如 To: First Last <[电子邮件受保护]>,其他用户 <[电子邮件受保护]>因此不推荐您的代码示例,因为它将无法传递此邮件,因为仅通过将其拆分为您仍然没有有效的地址!

You need to understand the difference between the visible address of an email, and the delivery.

msg["To"] is essentially what is printed on the letter. It doesn't actually have any effect. Except that your email client, just like the regular post officer, will assume that this is who you want to send the email to.

The actual delivery however can work quite different. So you can drop the email (or a copy) into the post box of someone completely different.

There are various reasons for this. For example forwarding. The To: header field doesn't change on forwarding, however the email is dropped into a different mailbox.

The smtp.sendmail command now takes care of the actual delivery. email.Message is the contents of the letter only, not the delivery.

In low-level SMTP, you need to give the receipients one-by-one, which is why a list of adresses (not including names!) is the sensible API.

For the header, it can also contain for example the name, e.g. To: First Last <[email protected]>, Other User <[email protected]>. Your code example therefore is not recommended, as it will fail delivering this mail, since just by splitting it on , you still not not have the valid adresses!

梦萦几度 2025-01-02 15:25:31

这对我有用。

import smtplib
from email.mime.text import MIMEText

s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = '[email protected]'
recipients = '[email protected],[email protected]'
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = recipients
s.sendmail(sender, recipients.split(','), msg.as_string())

It works for me.

import smtplib
from email.mime.text import MIMEText

s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = '[email protected]'
recipients = '[email protected],[email protected]'
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = recipients
s.sendmail(sender, recipients.split(','), msg.as_string())
终止放荡 2025-01-02 15:25:31

下面的解决方案对我有用。它成功地将电子邮件发送给多个收件人,包括“抄送”和“密件抄送”。

toaddr = ['mailid_1','mailid_2']
cc = ['mailid_3','mailid_4']
bcc = ['mailid_5','mailid_6']
subject = 'Email from Python Code'
fromaddr = 'sender_mailid'
message = "\n  !! Hello... !!"

msg['From'] = fromaddr
msg['To'] = ', '.join(toaddr)
msg['Cc'] = ', '.join(cc)
msg['Bcc'] = ', '.join(bcc)
msg['Subject'] = subject

s.sendmail(fromaddr, (toaddr+cc+bcc) , message)

The solution below worked for me. It successfully sends an email to multiple recipients, including "CC" and "BCC."

toaddr = ['mailid_1','mailid_2']
cc = ['mailid_3','mailid_4']
bcc = ['mailid_5','mailid_6']
subject = 'Email from Python Code'
fromaddr = 'sender_mailid'
message = "\n  !! Hello... !!"

msg['From'] = fromaddr
msg['To'] = ', '.join(toaddr)
msg['Cc'] = ', '.join(cc)
msg['Bcc'] = ', '.join(bcc)
msg['Subject'] = subject

s.sendmail(fromaddr, (toaddr+cc+bcc) , message)
苏大泽ㄣ 2025-01-02 15:25:31

所以实际上问题是 SMTP.sendmail 和 email.MIMEText 需要两个不同的东西。

email.MIMEText 设置电子邮件正文的“收件人:”标头。它仅用于向另一端的人员显示结果,并且像所有电子邮件标题一样,必须是单个字符串。 (请注意,它实际上与实际接收邮件的人没有任何关系。)

另一方面,SMTP.sendmail 为 SMTP 协议设置邮件的“信封”。它需要一个 Python 字符串列表,每个字符串都有一个地址。

因此,您需要做的就是合并您收到的两个回复。将 msg['To'] 设置为单个字符串,但将原始列表传递给 sendmail:

emails = ['a.com','b.com', 'c.com']
msg['To'] = ', '.join( emails ) 
....
s.sendmail( msg['From'], emails, msg.as_string())

So actually the problem is that SMTP.sendmail and email.MIMEText need two different things.

email.MIMEText sets up the "To:" header for the body of the e-mail. It is ONLY used for displaying a result to the human being at the other end, and like all e-mail headers, must be a single string. (Note that it does not actually have to have anything to do with the people who actually receive the message.)

SMTP.sendmail, on the other hand, sets up the "envelope" of the message for the SMTP protocol. It needs a Python list of strings, each of which has a single address.

So, what you need to do is COMBINE the two replies you received. Set msg['To'] to a single string, but pass the raw list to sendmail:

emails = ['a.com','b.com', 'c.com']
msg['To'] = ', '.join( emails ) 
....
s.sendmail( msg['From'], emails, msg.as_string())
尤怨 2025-01-02 15:25:31
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def sender(recipients): 

    body = 'Your email content here'
    msg = MIMEMultipart()

    msg['Subject'] = 'Email Subject'
    msg['From'] = '[email protected]'
    msg['To'] = (', ').join(recipients.split(','))

    msg.attach(MIMEText(body,'plain'))

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login('[email protected]', 'yourpassword')
    server.send_message(msg)
    server.quit()

if __name__ == '__main__':
    sender('[email protected],[email protected]')

它仅适用于我使用 send_message 函数并使用收件人列表中的 join 函数,python 3.6。

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

def sender(recipients): 

    body = 'Your email content here'
    msg = MIMEMultipart()

    msg['Subject'] = 'Email Subject'
    msg['From'] = '[email protected]'
    msg['To'] = (', ').join(recipients.split(','))

    msg.attach(MIMEText(body,'plain'))

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login('[email protected]', 'yourpassword')
    server.send_message(msg)
    server.quit()

if __name__ == '__main__':
    sender('[email protected],[email protected]')

It only worked for me with send_message function and using the join function in the list whith recipients, python 3.6.

故事与诗 2025-01-02 15:25:31

我尝试了下面的方法,效果非常好:)

rec_list =  ['[email protected]', '[email protected]']
rec =  ', '.join(rec_list)

msg['To'] = rec

send_out = smtplib.SMTP('localhost')
send_out.sendmail(me, rec_list, msg.as_string())

I tried the below and it worked like a charm :)

rec_list =  ['[email protected]', '[email protected]']
rec =  ', '.join(rec_list)

msg['To'] = rec

send_out = smtplib.SMTP('localhost')
send_out.sendmail(me, rec_list, msg.as_string())
橪书 2025-01-02 15:25:31

我想出了这个可导入的模块函数。在此示例中它使用 gmail 电子邮件服务器。它分为标题和消息,因此您可以清楚地看到发生了什么:

import smtplib

def send_alert(subject=""):

    to = ['[email protected]', 'email2@another_email.com', '[email protected]']
    gmail_user = '[email protected]'
    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()

I came up with this importable module function. It uses the gmail email server in this example. Its split into header and message so you can clearly see whats going on:

import smtplib

def send_alert(subject=""):

    to = ['[email protected]', 'email2@another_email.com', '[email protected]']
    gmail_user = '[email protected]'
    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()
榆西 2025-01-02 15:25:31

我使用 python 3.6,以下代码对我有用

email_send = '[email protected],[email protected]'
server.sendmail(email_user,email_send.split(','),text)    

I use python 3.6 and the following code works for me

email_send = '[email protected],[email protected]'
server.sendmail(email_user,email_send.split(','),text)    
最佳男配角 2025-01-02 15:25:31

几个月前我就发现了这个问题 关于它的博客。总结是:

如果你想使用 smtplib 向多个收件人发送电子邮件,请使用 email.Message.add_header('To', everyRecipientAsString) 添加它们,然后当你调用 sendmail 方法时, 使用 email.Message.get_all('To') 将消息发送给所有人。对于抄送和密件抄送收件人也是如此。

I figured this out a few months back and blogged about it. The summary is:

If you want to use smtplib to send email to multiple recipients, use email.Message.add_header('To', eachRecipientAsString) to add them, and then when you invoke the sendmail method, use email.Message.get_all('To') send the message to all of them. Ditto for Cc and Bcc recipients.

撩人痒 2025-01-02 15:25:31

好吧, this asnwer 方法中的方法对我不起作用。我不知道,也许这是一个Python3(我使用的是3.4版本)或gmail相关的问题,但经过一番尝试,对我有用的解决方案是行

s.send_message(msg)

而不是

s.sendmail(sender, recipients, msg.as_string())

Well, the method in this asnwer method did not work for me. I don't know, maybe this is a Python3 (I am using the 3.4 version) or gmail related issue, but after some tries, the solution that worked for me, was the line

s.send_message(msg)

instead of

s.sendmail(sender, recipients, msg.as_string())
明天过后 2025-01-02 15:25:31

这是一个老问题了。我发布新答案的主要原因是解释如何使用 Python 3.6+ 中的现代 email 库解决问题以及它与旧版本有何不同;但首先,让我们回顾一下 Anony-Mousse 在 他们 2012 年的答案中写的内容。

SMTP 根本不关心标头中的内容。您传递给 sendmail 方法的收件人列表实际上决定了邮件的发送位置。

在 SMTP 术语中,这称为邮件的信封。在协议级别,您连接到服务器,然后告诉它邮件来自谁(MAIL FROM: SMTP 动词)以及将其发送给谁(RCPT TO:),然后单独传输消息本身(DATA)以及标头和正文作为一个不透明的字符串 blob。

现代的 smtplib 通过提供一个 send_message 方法来简化 Python 方面,该方法实际上发送到消息标头中指定的收件人。

现代的email库提供了一个EmailMessage对象,它取代了过去您必须使用的所有各种单独的MIME类型来将较小的部分组装成消息。您可以添加附件而无需单独构建它们,并根据需要构建各种更复杂的多部分结构,但通常不需要这样做。只需创建一条消息并填充您想要的部分即可。

请注意,以下内容被大量评论;总体而言,新的 EmailMessage API 比旧 API 更加简洁更加通用。

from email.message import EmailMessage

msg = EmailMessage()

# This example uses explicit strings to emphasize that
# that's what these header eventually get turned into
msg["From"] = "[email protected]"
msg["To"] = "[email protected], [email protected]"
msg["Cc"] = "[email protected], [email protected]"
msg["Bcc"] = "[email protected], [email protected]"
msg["Subject"] = "Hello from the other side"

msg.set_content("This is the main text/plain message.")
# You can put an HTML body instead by adding a subtype string argument "html"
# msg.set_content("<p>This is the main text/html message.</p>", "html")

# You can add attachments of various types as you see fit;
# if there are no other parts, the message will be a simple
# text/plain or text/html, but Python will change it into a
# suitable multipart/related or etc if you add more parts
with open("image.png", "rb") as picture:
    msg.add_attachment(picture.read(), maintype="image", subtype="png")

# Which port to use etc depends on the mail server.
# Traditionally, port 25 is SMTP, but modern SMTP MSA submission uses 587.
# Some servers accept encrypted SMTP_SSL on port 465.
# Here, we use SMTP instead of SMTP_SSL, but pivot to encrypted
# traffic with STARTTLS after the initial handshake.
with smtplib.SMTP("smtp.example.org", 587) as server:
    # Some servers insist on this, others are more lenient ...
    # It is technically required by ESMTP, so let's do it
    # (If you use server.login() Python will perform an EHLO first
    # if you haven't done that already, but let's cover all bases)
    server.ehlo()
    # Whether or not to use STARTTLS depends on the mail server
    server.starttls()
    # Bewilderingly, some servers require a second EHLO after STARTTLS!
    server.ehlo()
    # Login is the norm rather than the exception these days
    # but if you are connecting to a local mail server which is
    # not on the public internet, this might not be useful or even possible
    server.login("[email protected]", "xyzzy")

    # Finally, send the message
    server.send_message(msg)

Bcc: 标头的最终可见性取决于邮件服务器。如果您想真正确保收件人彼此不可见,也许根本不要放置Bcc:标头,并单独枚举信封收件人像您以前使用 sendmail 那样的信封(send_message 也可以让您这样做,但如果您只想发送给指定的收件人,则不必这样做标题)。

显然,这会一次性向所有收件人发送一条消息。如果您要向很多人发送相同的消息,这通常是您应该做的。但是,如果每条消息都是唯一的,您将需要遍历收件人并为每条消息创建并发送新消息。 (仅仅希望将收件人的姓名和地址放在 To: 标头中可能不足以保证发送比所需数量更多的消息,但是当然,有时正文中的每个收件人都有唯一的内容, 也。)

This is an old question. My main reason to post a new answer is to explain how to solve the problem with the modern email library in Python 3.6+ and how it differs from the old version; but first, let's recap what Anony-Mousse wrote in their answer from 2012.

SMTP doesn't care at all what's in the headers. The list of recipients you pass in to the sendmail method are what actually determine where the message will be delivered.

In SMTP parlance, this is called the message's envelope. On the protocol level, you connect to the server, then tell it who the message is from (MAIL FROM: SMTP verb) and who to send it to (RCPT TO:), then separately transmit the message itself (DATA) with headers and body as one opaque string blob.

The modern smtplib simplifies the Python side of this by providing a send_message method which actually sends to the recipients specified in the message's headers.

The modern email library provides an EmailMessage object which replaces all the various individual MIME types which you had to use in the past to assemble a message from smaller parts. You can add attachments without separately constructing them, and build various more complex multipart structures if you need to, but you normally don't have to. Just create a message and populate the parts you want.

Notice that the following is heavily commented; on the whole, the new EmailMessage API is more succinct and more versatile than the old API.

from email.message import EmailMessage

msg = EmailMessage()

# This example uses explicit strings to emphasize that
# that's what these header eventually get turned into
msg["From"] = "[email protected]"
msg["To"] = "[email protected], [email protected]"
msg["Cc"] = "[email protected], [email protected]"
msg["Bcc"] = "[email protected], [email protected]"
msg["Subject"] = "Hello from the other side"

msg.set_content("This is the main text/plain message.")
# You can put an HTML body instead by adding a subtype string argument "html"
# msg.set_content("<p>This is the main text/html message.</p>", "html")

# You can add attachments of various types as you see fit;
# if there are no other parts, the message will be a simple
# text/plain or text/html, but Python will change it into a
# suitable multipart/related or etc if you add more parts
with open("image.png", "rb") as picture:
    msg.add_attachment(picture.read(), maintype="image", subtype="png")

# Which port to use etc depends on the mail server.
# Traditionally, port 25 is SMTP, but modern SMTP MSA submission uses 587.
# Some servers accept encrypted SMTP_SSL on port 465.
# Here, we use SMTP instead of SMTP_SSL, but pivot to encrypted
# traffic with STARTTLS after the initial handshake.
with smtplib.SMTP("smtp.example.org", 587) as server:
    # Some servers insist on this, others are more lenient ...
    # It is technically required by ESMTP, so let's do it
    # (If you use server.login() Python will perform an EHLO first
    # if you haven't done that already, but let's cover all bases)
    server.ehlo()
    # Whether or not to use STARTTLS depends on the mail server
    server.starttls()
    # Bewilderingly, some servers require a second EHLO after STARTTLS!
    server.ehlo()
    # Login is the norm rather than the exception these days
    # but if you are connecting to a local mail server which is
    # not on the public internet, this might not be useful or even possible
    server.login("[email protected]", "xyzzy")

    # Finally, send the message
    server.send_message(msg)

The ultimate visibility of the Bcc: header depends on the mail server. If you want to be really sure that the recipients are not visible to each other, perhaps don't put a Bcc: header at all, and separately enumerate the envelope recipients in the envelope like you used to have to with sendmail (send_message lets you do that too, but you don't have to if you just want to send to the recipients named in the headers).

This obviously sends a single message to all recipients in one go. That is generally what you should be doing if you are sending the same message to a lot of people. However, if each message is unique, you will need to loop over the recipients and create and send a new message for each. (Merely wishing to put the recipient's name and address in the To: header is probably not enough to warrant sending many more messages than required, but of course, sometimes you have unique content for each recipient in the body, too.)

微凉 2025-01-02 15:25:31

尝试将所有收件人和 cc_recipients 声明为字符串的列表变量,而不是循环遍历它们,如下所示:

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import smtplib

recipients = ["[email protected]","[email protected]", "[email protected]"]
cc_recipients=["[email protected]", "[email protected]"]
msg = MIMEMultipart()
msg["Subject"] = "Example"
msg["From"] = "[email protected]"
msg["To"] = ', '.join(recipients)
msg["Cc"] = ', '.join(cc_recipients)
body = MIMEText("example email body")
msg.attach(body)
smtp = smtplib.SMTP("mailhost.example.com", 25)
for recipient in recipients:
    smtp.sendmail(msg["From"], recipient, msg.as_string())
for cc_recipient in cc_recipients:
    smtp.sendmail(msg["From"], cc_recipient, msg.as_string())
smtp.quit()

Try declaring a list variable with all recipients and cc_recipients as strings than looping over them, like this:

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import smtplib

recipients = ["[email protected]","[email protected]", "[email protected]"]
cc_recipients=["[email protected]", "[email protected]"]
msg = MIMEMultipart()
msg["Subject"] = "Example"
msg["From"] = "[email protected]"
msg["To"] = ', '.join(recipients)
msg["Cc"] = ', '.join(cc_recipients)
body = MIMEText("example email body")
msg.attach(body)
smtp = smtplib.SMTP("mailhost.example.com", 25)
for recipient in recipients:
    smtp.sendmail(msg["From"], recipient, msg.as_string())
for cc_recipient in cc_recipients:
    smtp.sendmail(msg["From"], cc_recipient, msg.as_string())
smtp.quit()
十年九夏 2025-01-02 15:25:31

当您在文本文件中写入收件人电子邮件时可以尝试此操作

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 = "[email protected]"
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')

you can try this when you write the recpient emails on a text file

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 = "[email protected]"
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')
请爱~陌生人 2025-01-02 15:25:31

这里有很多技术上或部分正确的答案。在阅读了每个人的答案后,我想出了这是一个更可靠/通用的电子邮件功能。我已经确认它有效,您可以传递 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="[email protected]", 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() 想要一个 List 而不是 String!函数适用于Python3.6+

There are a lot of answers on here that are technically or partially correct. After reading everyone's answers, I came up with this as a more solid/universal email function. I have confirmed it works and you can pass HTML or plain text for the body. Note that this code does not include attachment code:

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="[email protected]", 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()

This can obviously be modified to use native Python logging. I am just providing a solid core function. I also can't stress this enough, sendmail() wants a List and NOT a String! Function is for Python3.6+

Bonjour°[大白 2025-01-02 15:25:31

对于那些希望发送仅包含一个“To”标头的消息的人,下面的代码可以解决这个问题。确保您的接收者变量是字符串列表。

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = title
msg['From'] = f'support@{config("domain_base")}'
msg['To'] =  "me"
message_content += f"""
    <br /><br />
    Regards,<br />
    Company Name<br />
    The {config("domain_base")} team
"""
body = MIMEText(message_content, 'html')
msg.attach(body)

try:
    smtpObj = smtplib.SMTP('localhost')
    for r in receivers:
        del msg['To']
        msg['To'] =  r #"Customer /n" + r
        smtpObj.sendmail(f"support@{config('domain_base')}", r, msg.as_string())
    smtpObj.quit()      
    return {"message": "Successfully sent email"}
except smtplib.SMTPException:
    return {"message": "Error: unable to send email"}

For those who wish to send the message with only one 'To' header, the code below solves it. Ensure that your receivers variable is a list of strings.

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = title
msg['From'] = f'support@{config("domain_base")}'
msg['To'] =  "me"
message_content += f"""
    <br /><br />
    Regards,<br />
    Company Name<br />
    The {config("domain_base")} team
"""
body = MIMEText(message_content, 'html')
msg.attach(body)

try:
    smtpObj = smtplib.SMTP('localhost')
    for r in receivers:
        del msg['To']
        msg['To'] =  r #"Customer /n" + r
        smtpObj.sendmail(f"support@{config('domain_base')}", r, msg.as_string())
    smtpObj.quit()      
    return {"message": "Successfully sent email"}
except smtplib.SMTPException:
    return {"message": "Error: unable to send email"}
深爱不及久伴 2025-01-02 15:25:31

要将电子邮件发送给多个收件人,请将收件人添加为电子邮件 ID 列表。

receivers = ['[电子邮件受保护]', '[电子邮件受保护]', '[电子邮件受保护]']

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

smtp_server = 'smtp-example.com'
port = 26 
sender = '[email protected]'
debuglevel = 0

# add receivers as list of email id string
receivers = ['[email protected]', '[email protected]', '[email protected]']

message = MIMEMultipart(
    "mixed", None, [MIMEImage(img_data, 'png'), MIMEText(html,'html')])
    message['Subject'] = "Token Data"
    message['From'] = sender
    message['To'] = ", ".join(receivers)
    try:

        server = smtplib.SMTP('smtp-example.com')
        server.set_debuglevel(1)
        server.sendmail(sender, receivers, message.as_string())
        server.quit()
        # print(response)

    except BaseException:
        print('Error: unable to send email')

To send email to multiple recipients add receivers as list of email id.

receivers = ['[email protected]', '[email protected]', '[email protected]']

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

smtp_server = 'smtp-example.com'
port = 26 
sender = '[email protected]'
debuglevel = 0

# add receivers as list of email id string
receivers = ['[email protected]', '[email protected]', '[email protected]']

message = MIMEMultipart(
    "mixed", None, [MIMEImage(img_data, 'png'), MIMEText(html,'html')])
    message['Subject'] = "Token Data"
    message['From'] = sender
    message['To'] = ", ".join(receivers)
    try:

        server = smtplib.SMTP('smtp-example.com')
        server.set_debuglevel(1)
        server.sendmail(sender, receivers, message.as_string())
        server.quit()
        # print(response)

    except BaseException:
        print('Error: unable to send email')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文