麻烦这个电子邮件附件和PDF?

时间:2015-12-08 10:19:23

标签: python-3.x

我正在使用我在这里找到的代码。我正在尝试将pdf作为附件发送,但它无法正常工作。我可以发送电子邮件

def Email():
    import os
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage
    from email.mime.multipart import MIMEMultipart
    msg = MIMEMultipart()
    msg.attach(MIMEText(file("John.pdf").read()))



    server = smtplib.SMTP('smtp.mail.yahoo.com')

    To = ''
    SUBJECT = name
    TEXT = 'This is your bill' '\n' ,int(thesum),\
    'Your total distance is ',int(totalDistance),\
    'Yur best route is '' ,  '.join(root),\

    server.ehlo()
    server.starttls()
    server.ehlo()

    msg = 'Subject: %s\n\n%s' % (SUBJECT, TEXT)


    server.login("", "")

    server.sendmail("",To, msg)
    print('sent')

Email()

我收到以下错误:

   msg.attach(MIMEText(file("John.pdf").read()))
   NameError: name 'file' is not defined

2 个答案:

答案 0 :(得分:0)

file不是一个功能。 也许你想做这样的事情:

with open('John.pdf', 'r') as f:
    s = f.read()

然后添加s作为附件。

msg.attach(MIMEText(s))

(但我不确定如何使用与电子邮件相关的内容;也许您必须对其进行base64编码并使用MIMEApplication()作为pdf文件;也许其他人可以为您解答此问题)

答案 1 :(得分:0)

def Email():
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()

msg.attach(MIMEText("John.pdf"))


server = smtplib.SMTP('smtp.mail.yahoo.com')

To = ''
SUBJECT = name
TEXT = 'This is your bill' '\n' ,int(thesum),\
'Your total distance is ',int(totalDistance),\
'Yur best route is '' ,  '.join(root),\

server.ehlo()
server.starttls()
server.ehlo()

msg = 'Subject: %s\n\n%s' % (SUBJECT, TEXT)


server.login("", "")

server.sendmail("",To, msg.as_string())
print('sent')