Python邮件脚本添加Cc功能时遭遇smtplib.SMTPAuthenticationError认证失败问题求助
解决SMTP认证失败与抄送功能问题
首先看你遇到的两个核心问题:SMTP认证失败,还有虽然设置了msg["Cc"]但实际抄送功能可能无法正常工作(即使认证通过后),我来一步步帮你解决:
一、修复SMTPAuthenticationError (535)
这个错误是Office365拒绝了你的认证请求,常见原因和对应解决办法:
使用应用密码(若开启MFA):
如果你的Office365账户开启了多因素认证(MFA),直接用日常登录密码是无效的,需要生成一个应用专用密码。操作路径大概是:登录微软账户→进入安全设置→找到"应用密码"选项→生成新的应用密码,把这个密码替换代码里的password字段。检查账户SMTP访问权限:
部分企业版Office365可能被管理员禁用了SMTP协议访问,你可以联系IT管理员确认你的账户是否允许使用SMTP发送邮件。确认密码准确性:
如果没开MFA,先仔细核对password的大小写、特殊字符,确保没有输入错误。
二、正确实现抄送(Cc)功能
你的代码里已经设置了邮件头的msg["Cc"],但server.sendmail()的第二个参数只传了主收件人,这会导致抄送人收不到邮件——因为邮件头的Cc只是显示用,实际发送时需要把主收件人和抄送人都加入收件人列表:
修改这一行:
server.sendmail(email, send_to_email, text)
改成:
# 合并主收件人和抄送人到同一列表 recipients = [send_to_email] + [cc] server.sendmail(email, recipients, text)
如果有多个抄送人(比如cc是逗号分隔的字符串"cc1@example.com,cc2@example.com"),可以拆分后加入列表:
recipients = [send_to_email] + [addr.strip() for addr in cc.split(',')] server.sendmail(email, recipients, text)
这样既会在邮件头显示抄送人,同时这些地址也能实际收到邮件。
完整修正后的代码
整合上述修改后的代码示例:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText email = "my addr" # 若开启MFA,请替换为应用专用密码 password = "your_app_password_or_regular_password" send_to_email = "destination@example.com" cc = "cc_mail@example.com" subject = "hello" message = "hello" msg = MIMEMultipart() msg["From"] = email msg["To"] = send_to_email msg["Cc"] = cc msg["Subject"] = subject msg.attach(MIMEText(message, 'plain')) server = smtplib.SMTP("smtp.office365.com", 587) server.starttls() server.login(email, password) text = msg.as_string() # 合并收件人与抄送人列表 recipients = [send_to_email] + [cc] server.sendmail(email, recipients, text) server.quit()
内容的提问来源于stack exchange,提问作者Dave dave
相关产品推荐
相关产品推荐

