电子邮件只发送给第一个收件人smtp邮件python

5

我知道,有数百个问题都是相同的查询。对此我感到抱歉。我几乎尝试了每一个解决方案。但仍然没有得到解决。实际上,我从stackoverflow的一个查询中复制了一些代码,并根据我的要求进行了改进。

我正在编写一个使用Python向我们的服务器发送错误报告的脚本。我的问题是只有发送给RECIPIENTS的第一个成员。 它需要同时发送给管理团队和管理员。

RECIPIENTS = ["mail1@gmail.com", 'mail2@mydomain.in' ]
TO = ", ".join(RECIPIENTS)
USER = "user30@gmail.com"
PASSWD = "userpass"

def sendmail():
    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject()
    msg['From'] = USER
    msg['To'] = TO
    mime_text = MIMEText(get_msg_text(), 'plain')
    msg.attach(mime_text)

    #-- Auth by Gmail
    SERVER = smtplib.SMTP("smtp.gmail.com:587")
    SERVER.starttls()

    try:
       SERVER.login(USER,PASSWD)
    except SMTPAuthenticationError, e:
        logit(e)
        return False

    try:    
        SERVER.sendmail(msg['From'], msg['To'], msg.as_string())
    except Exception, e:
        logit(e)
        return False
    finally:
        SERVER.quit()
    return True


if __name__ == "__main__":
   sendmail()

注意:所有提到的函数和模块都已正确 import。实际上,它能够成功地发送邮件。

我尝试遵循旧帖子:


@所有人:在执行-1操作前,请注明原因。如果您无法说明原因,则不是执行该操作的合适人选。 - trex
@nu11p01n73R - 我也尝试了,但出现了错误“list没有lstrip()对象”。 - trex
@nu11p01n73R:请问你能提供文档或语法的链接吗?谢谢。 - trex
你有没有找到解决办法? - pyramidface
编辑:算了,对于那些偶然发现这个帖子的人,我在得票最高的答案中找到了解决方案:https://dev59.com/oWox5IYBdhLWcg3w95A9 - pyramidface
其他解决方案请参考 https://dev59.com/wITba4cB1Zd3GeqP8p-0#64947133 - tnusraddinov
4个回答

1
要将电子邮件发送给多个人,您需要在sendmail函数中传递一个列表而不是字符串。这对您来说将起作用。
try:    
    SERVER.sendmail(msg['From'], RECIPIENTS, msg.as_string())
except Exception, e:
    logit(e)
    return False

0

这是一个相当旧的帖子,但以防其他人遇到同样的问题。 我们遇到了同样的问题,唯一的解决方法是使用MIMEMultipart:

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

email_to = ['foo@here.com', 'bar@there.com', 'dumb@a.com']
msg = MIMEMultipart('related')
msg['Subject'] = " You Tell me"
msg['From'] = "noReply@every.com"
msg['To'] = ", ".join(email_to)
#if reply_to:
#   msg['Reply-to'] = reply_to

part1 = MIMEText("WHY ME?!?!!", 'html')
msg.attach(part1)

s = smtplib.SMTP('smtp.server.com')
s.sendmail("whyme@here.com", email_to, msg.as_string())
s.quit()

0

我尝试了这篇文章中的所有组合以及推荐的方法,但是使用Python3时无法使其正常工作。这是我唯一成功的方法。它并不完美,因为接收电子邮件的人没有收到所有被发送的电子邮件。

  for email in SMTP["to"]:
       msg = MIMEMultipart()
       msg['From'] = SMTP["user"]
       msg['To'] = email
       msg['Subject'] = f"[Repoman Notifier] Run on {today}!"
       msg.attach(MIMEText(html_builder(report_data), 'html'))

       server = smtplib.SMTP(f'{SMTP["host"]}:{SMTP["port"]}')
       server.starttls()
       server.login(msg['From'], SMTP["password"])

       server.send_message(msg, msg['From'], msg["to"])

       server.quit()

-1
在你的第一个电子邮件中,你使用了",但在第二个电子邮件中你使用了'。尝试删除'并替换为"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接