Attachments getting attached twice using smptplib in python

1.3k views Asked by At

I am trying to implement a functionality in python where I want to send a file as an attachment to an email alert Everything works fine. i am getting the email alert with required subject but the only problem is that I get the same attachment twice in my email alert.

    fileMsg = email.mime.base.MIMEBase('application','octet-stream')
    fileMsg.set_payload(file('/home/bsingh/python_files/file_dict.txt').read())
    #email.encoders.encode_base64(fileMsg)
    fileMsg.add_header('Content-Disposition','attachment;filename=LogFile.txt')
    emailMsg.attach(fileMsg)

  # send email
    server = smtplib.SMTP(smtp_server)
    server.starttls()
    server.login(username, password)
    server.sendmail(from_add, to_addr,emailMsg.as_string())
    server.quit()
3

There are 3 answers

0
Shruti Srivastava On BEST ANSWER

There was an issue with the version..Has been resolved

11
PascalVKooten On

The whole purpose of yagmail (I'm the developer) is to make it really easy to send emails, especially with HTML or attachment needs.

Please try the following code:

import yagmail
yag = yagmail.SMTP(from_add, password)
contents = ['See my attachment below', '/home/bsingh/python_files/file_dict.txt']
yag.send(contents = contents)

Notice the magic here: contents is a list, where an item equal to a file path will automatically be loaded, mimetype guessed, and attached.

There's a lot more magic involved, such as easy to embed images, passwordless scripts, usernameless scripts, easy aliases, smart defaults (notice I omitted the to and subject arguments?) and much more. I advise/encourage you to read its github page :-). Feel free to raise issues or add feature requests!

You can get yagmail by using pip to install it:

pip install yagmail # Python 2
pip3 install yagmail # Python 3
2
keisetsu On

I have been having problems with this myself. I had 'alternative' as my message's MIMEMultipart type. When I changed to the default, 'mixed', the duplicate disappeared.

So if you created emailMsg using MIMEMultipart('alternative'), you may have the same problem.

I believe 'alternative' is for offering both a text and html version of the message body, so I think you need to offer both in addition to your attachment if you use it.

I hope that helps.

I have not found a good explanation of this anywhere yet; email can get pretty complicated.