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

时间:2014-05-29 06:50:26

标签: python file email text

这是我的代码,它可以工作,但我想发送.text文件和它一起多于4个。 我该怎么做呢?谢谢!

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

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

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

1 个答案:

答案 0 :(得分:0)

我使用它来发送带有附件的邮件:

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