gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:50:14 25 4
gpt4 key购买 nike

我对用 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 来实现此目的(以下是文档: https://docs.python.org/3.4/library/email-examples.html )

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

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()

关于python - 向多人发送带有附件的电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56261843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com