在Python电子邮件中附加PNG图像

时间:2017-01-20 16:07:11

标签: python image email email-attachments

我想通过显示徽标的python发送电子邮件。图像是同一目录中的png图像。

我使用了我在这里找到的简单代码,但是当我将它发送到我自己的帐户时,没有图像。没有附件可供参考以生成图像。有人可以告诉我我错过了什么吗?

from tkinter import *
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import csv
import time
from string import Template
import warnings

root = Tk()
root.geometry('200x200')

email_label = Label(root, text="Enter your email")
email_label.pack()

username = Entry(root, width = 30)
username.pack()

password_label = Label(root, text="Enter your password")
password_label.pack()

password = Entry(root, show="*", width = 30)
password.pack()


def add_var():
    a = 0
    user_name = username.get()
    pass_word = password.get()
    with open("emailtk.csv") as f:
        reader = csv.reader(f)
        for row in reader:
            a+=1
            time.sleep(3)
            try:
                address = row[0]
                first_name = row[1]
                last_name = row[2]
                name = first_name+last_name
                company = row[4]
                print("Event", a)
                print("Will now send an email to %s %s at %s at %s" % (first_name, last_name, company, address))
                msg = MIMEMultipart('alternative')
                msg['Subject'] = "Link"
                msg['From'] = user_name
                msg['To'] = address
                html = """\
                <html>
                  <head></head>
                  <body>
                    <p>
                      stuff
                    </p>
                  </body>
                </html>
                """.format(n = name, org = company)
                part1 = MIMEText(html, 'html')
                msg.attach(part1)

                img = "logo.png"
                img_data = open(img, "rb").read()
                image = MIMEImage(img_data, name = os.path.basename(img))
                msg.attach(image)
                msg.attach(msgImage)

                s = smtplib.SMTP('Server.com', Socket)
                s.ehlo()
                s.starttls()
                s.login(user_name,pass_word)
                s.sendmail(user_name, address, msg.as_string())
                print("email sent")
                s.quit()
            except:
            pass
            print("Done")

button = Button(root, text = "Submit", command = add_var)
button.pack()

root.mainloop()

以下是我用来附加图片的代码:

img = "logo.png"
img_data = open(img, "rb").read()
image = MIMEImage(img_data, name = os.path.basename(img))
msg.attach(image)

1 个答案:

答案 0 :(得分:0)

试试这个

添加标题

  

msg.add_header('Content-Disposition','attachment',filename = filename)

查看此网站

JavaDoc