使用smtplib添加电子邮件附件

时间:2018-02-27 17:07:58

标签: python email smtp smtplib

我试图发送电子邮件并附上VCF文件,但我遇到了一些麻烦。我设法发送了纯文本的电子邮件而没有任何问题,但这是我现在运行代码时遇到的错误:

AttributeError: 'file' object has no attribute 'rfind'

我的代码:

import vobject
import requests
import smtplib
from os.path import basename
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
j = vobject.vCard()
j.add('n')
j.n.value = vobject.vcard.Name(family='Harris', given='Jeffrey')
j.add('fn')
j.fn.value = 'Jeffrey Harris'
j.add('email')
j.email.value = 'jeffrey@osafoundation.org'
j.email.type_param = 'Internet'

k = j.serialize()

with open ('new.vcf', 'w') as file:
    file.write(k)

with open('new.vcf', 'rb') as fil:
    part = MIMEApplication(
        fil.read(),
        Name=basename(fil)
    )
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(fil)

msg = MIMEMultipart()
msg['From'] = 'me@myemail.com'
msg['To'] = 'me@myemail.com'
msg['Subject'] = 'test'
message = 'test'
msg.attach(part)

mailserver = smtplib.SMTP('secure.emailsrvr.com',587)
mailserver.ehlo()
mailserver.starttls()
mailserver.ehlo()
mailserver.login('me@myemail.com', 'mypassword')
mailserver.sendmail('me@myemail.com','me@myemail.com',msg.as_string())

mailserver.quit()

关于我做错的任何想法?

1 个答案:

答案 0 :(得分:1)

您的问题出在Name=basename(fil),因为basename()接受strbytesos.PathLike对象。

您正试图将_io.BudderReader作为参数传递。

<强>解决方案:

您应该传递附件的文件名(OP案例为new.vcf)。