简体   繁体   中英

Adding email attachments using smtplib

I'm trying to send emails and attach a VCF file, but I'm running into some trouble. I've managed to send emails with plain text without any issues, but here's the error I'm getting when I run my code now:

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

And my code:

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

Any ideas on what I'm doing wrong?

Your problem is in Name=basename(fil) because basename() accept str , bytes or os.PathLike object.

You are trying to pass _io.BudderReader as an argument.

Solution:

You should pass the filename of the attachment (in OP case is new.vcf ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM