Skip to main content
 首页 » 编程设计

python之从分发邮件 ID [Python] 发送邮件的问题

2025年05月04日29tintown

看到下面的问题,还是有一些疑惑。

Sending an email from a distribution list

首先,我有一个个人邮件帐户以及一个用于特定邮件服务器中的组的分发 ID。只需指定 From 字段,我就可以通过 outlook 从分发邮件 ID 发送邮件。它不需要身份验证。

我一直在使用以下代码通过我的个人帐户发送邮件:

import smtplib 
from email.mime.multipart import MIMEMultipart 
from email.mime.text import MIMEText 
import os 
 
 
FROMADDR = "myaddr@server.com" 
GROUP_ADDR = ['group@server.com'] 
PASSWORD = 'foo' 
 
 
TOADDR   = ['toaddr@server.com'] 
CCADDR   = ['group@server.com'] 
 
# Create message container - the correct MIME type is multipart/alternative. 
msg            = MIMEMultipart('alternative') 
msg['Subject'] = 'Test' 
msg['From']    = FROMADDR 
msg['To']      = ', '.join(TOADDR) 
msg['Cc']      = ', '.join(CCADDR) 
 
# Create the body of the message (an HTML version). 
text = """Hi  this is the body 
""" 
 
# Record the MIME types of both parts - text/plain and text/html. 
body = MIMEText(text, 'plain') 
 
# Attach parts into message container. 
msg.attach(body) 
 
# Send the message via local SMTP server. 
s = smtplib.SMTP('server.com', 587) 
s.set_debuglevel(1) 
s.ehlo() 
s.starttls() 
s.login(FROMADDR, PASSWORD) 
s.sendmail(FROMADDR, TOADDR, msg.as_string()) 
s.quit() 

这工作得很好。由于我可以通过 outlook 从分发邮件 ID 发送邮件(无需任何密码),有什么方法可以修改此代码以通过分发 ID 发送邮件?我试着注释掉

s.ehlo() 
s.starttls() 
s.login(FROMADDR, PASSWORD) 

部分但代码给我以下错误:

send: 'mail FROM:<group@server.com> size=393\r\n' 
reply: b'530 5.7.1 Client was not authenticated\r\n' 
reply: retcode (530); Msg: b'5.7.1 Client was not authenticated' 
send: 'rset\r\n' 
Traceback (most recent call last): 
  File "C:\Send_Mail_new.py", line 39, in <module> 
    s.sendmail(FROMADDR, TOADDR, msg.as_string()) 
  File "C:\Python32\lib\smtplib.py", line 743, in sendmail 
    self.rset() 
  File "C:\Python32\lib\smtplib.py", line 471, in rset 
    return self.docmd("rset") 
  File "C:\Python32\lib\smtplib.py", line 395, in docmd 
    return self.getreply() 
  File "C:\Python32\lib\smtplib.py", line 371, in getreply 
    raise SMTPServerDisconnected("Connection unexpectedly closed") 
smtplib.SMTPServerDisconnected: Connection unexpectedly closed 

有人会好心帮助我吗?

请您参考如下方法:

回复:retcode (530);消息:b'5.7.1 客户端未通过身份验证'

这意味着您需要身份验证。 Outlook 可能对您现有的帐户使用相同的身份验证(因为您只更改了 From header )。