Python 向多人发送带有附件的电子邮件

Python 向多人发送带有附件的电子邮件,python,smtplib,Python,Smtplib,我对用python发送电子邮件真的很陌生。我可以发送带有附件的个人电子邮件,也可以发送不带附件的多封电子邮件,但我的代码无法发送多封电子邮件和附件 msg = MIMEMultipart() fromaddr = email_user toaddr = ["email"] cc = ["email2"] bcc = ["email3"] subject = "This is the subject" body = 'Message for

我对用python发送电子邮件真的很陌生。我可以发送带有附件的个人电子邮件,也可以发送不带附件的多封电子邮件,但我的代码无法发送多封电子邮件和附件

    msg = MIMEMultipart()
    fromaddr = email_user
    toaddr = ["email"]
    cc = ["email2"]
    bcc = ["email3"]

    subject = "This is the subject"
    body = 'Message for the email' 
    msg = "From: %s\r\n" % fromaddr+ "To: %s\r\n" % toaddr + "CC: %s\r\n" % ",".join(cc) + "Subject: %s\r\n" % subject + "\r\n" + body
    toaddr = toaddr + cc + bcc
    msg.attach(MIMEText(body,'plain'))
    filename ="excelfile.xlsx" 
    attachment=open(filename,'rb')
    part = MIMEBase('application','octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition',"attachment; filename= "+filename)
    msg.attach(part)
    text = msg.as_string()
    server = smtplib.SMTP('smtp.gmail.com',587)
    server.starttls()
    server.login(email_user,email_password)
    server.sendmail(fromaddr, toaddr, message) 
    server.quit()

我得到以下错误。。。AttributeError:“str”对象没有属性“attach”

您可以借助MIMEMultipart和MIMEText实现这一点(以下是文档:)

基本上,您只需使用以下内容创建附件:

msg=MIMEMultipart()
part = MIMEBase('application', "octet-stream")
part.set_payload(open("attachment.txt", "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="attachment.txt"')
并将其附加到电子邮件:

msg.attach(part)
以下是完整的代码:

import smtplib                                                                          #import libraries for sending Emails(with attachment)
#this is to attach the attachment file
from email.mime.multipart import MIMEMultipart
#this is for attaching the body of the mail
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

server = smtplib.SMTP('smtp.gmail.com', 587)                                            #connects to Email server
server.starttls()
server.user="your@email" 
server.password="yourpassw"
server.login(server.user, server.password)                                              #log in to server

#creates attachment
msg=MIMEMultipart()
part = MIMEBase('application', "octet-stream")
part.set_payload(open("attachment.txt", "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="attachment.txt"')

#attach the attachment
msg.attach(part)

#attach the body
msg.attach(MIMEText("your text"))

#sends mail with attachment
server.sendmail(server.user, ["user@1", "user@2", ...], msg=(msg.as_string()))
server.quit()

您正在将msg变量从MIMEMultipart重写为Str,行
msg=“from:%s\r\n”%fromaddr+…
哦,我明白了。那么我如何添加消息和附件呢?我不知道MiMemMultipart类及其api,但我只是注意到您正在覆盖变量。你可能想查看它的文档。请在你的答案上至少添加一个解释,以防止你被否决,不要只发布有意义的纯代码,但你把邮件正文放在哪里??