如何使用python代码向电子邮件添加附件?

2024-10-04 11:31:17 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码和它的工作,但我想与它一起发送多个约4.txt文件。 我该怎么做呢?谢谢您!在

import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)

server.login("Email@gamil.com", "password")

msg = "\n"
server.sendmail("From", "To", msg)

Tags: 文件代码importtxtcomserveremaillogin
1条回答
网友
1楼 · 发布于 2024-10-04 11:31:17

我用gmail发送带有附件的邮件:

def send_mail(send_from, send_to, files=[]):

        msg = MIMEMultipart()
        msg['From'] = send_from
        msg['To'] = send_to
        msg['Date'] = formatdate(localtime=True)
        if len(string_files)==1:
            msg['Subject'] = 'Sending file: %s' % files[0]
        else:
            msg['Subject'] = 'Sending file: %s and others' % files[0]
        text='This message has followng attachments'
        for filename in string_files:
            text+='\n%s' % filename
        msg.attach( MIMEText(text) )

        for f in files:
            part = MIMEBase('application', "octet-stream")
            part.set_payload( open(f,"rb").read() )
            encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
            msg.attach(part)

        smtp = smtplib.SMTP('smtp.gmail.com:587')
        smtp.starttls()

        # if you store password in a keyring (like gnome-keyring)
        import keyring
        gmail_password = keyring.get_password('gmail', 'personal')
        # or just gmail_password='password'
        smtp.login('yourgmailaddress', gmail_password)
        smtp.sendmail(send_from, send_to, msg.as_string())
        smtp.close()

相关问题 更多 >