发送多个文件附件邮件

Send multiple files attached mail

我想通过电子邮件发送两个文件附件,但我不知道该怎么做,有帮助吗?

def sendmail():
    sender_email = "sender@gmail.com"
    receiver_email = "receiver@gmail.com"
    message = MIMEMultipart()
    message["From"] = sender_email
    message['To'] = receiver_email
    message['Subject'] = "Deine Monatseinteilung"
    file = (f'{myPath}/File-2-2022.ics')
    attachment = open(file,'rb')
    obj = MIMEBase('application','octet-stream')
    obj.set_payload((attachment).read())
    encoders.encode_base64(obj)
    obj.add_header('Content-Disposition',"attachment; filename= "+file)
    message.attach(obj)
    my_message = message.as_string()
    email_session = smtplib.SMTP('smtp.gmail.com',587)
    email_session.starttls()
    email_session.login(sender_email,'xxxxxx')
    email_session.sendmail(sender_email,receiver_email,my_message)
    email_session.quit()
    print(f"Deine monatseinteilung wurde an deine E-Mail-Adresse gesendet ({receiver_email})")
sendmail()

尝试使用下面的代码片段:

import smtplib

from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate

def _send_email(send_from, send_to, subject, text, files=None):
    assert isinstance(send_to, list)

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(text))

    for f in files or []:
        with open(f, "rb") as fil:
            part = MIMEApplication(
                fil.read(),
                Name=basename(f)
            )
            
        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
        msg.attach(part)

    smtp = smtplib.SMTP(SERVER, PORT)
    smtp.login(USER, PASS)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()

然后你可以这样调用函数:

send_from = "fakeemail3@domain.com"
send_to = ['fakeemail1@domain.com', 'fakeemail2@domain.com']
subject = "My Subject"
text = "This is a email."
files = ["pathtofile1", "pathtofile2"]

_send_email(send_from, send_to, subject, text, files)