oneclick
oneclick

Reputation: 101

Sending mail with (docx)attachment using python

I have been trying to send a mail via python with a Docx attachment

I'm able to get a mail but with no attachment to it, below is the code I used for attaching a file And I didn't get any error while attaching a file

import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

sender_email = email
receiver_email = toemail
password = password

message = MIMEMultipart("alternative")
message["Subject"] = Subject
message["From"] = sender_email
message["To"] = receiver_email
message.attach(htmlmessage)

attach_file = open(attach_file_name, 'rb') # Open the file as binary mode
payload = MIMEBase('application', 'octet-stream')
payload.set_payload((attach_file).read())
encoders.encode_base64(payload)
#encode the attachment
#add payload header with filename
payload.add_header('Content-Disposition', "attachment; filename= %s" % attach_file)
message.attach(payload)

context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(
        sender_email, receiver_email, message.as_string()
    )




Upvotes: 0

Views: 954

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 149175

Mime types are to be respected. The type multipart/alternative should be used for messages containing the same information in plain text and in HTML. The mail reader can then choose which representation it can use.

On the other hand, multipart/mixed should be used when the message contains multiple different parts, said differently to transport attachements.

So, provided htmlmessage is a valid email.mime.text.MIMEText, your code should not declare "alternative":

...
message = MIMEMultipart()
...

Furthermore, you should avoid to directly use MIMEBase and instead rely on the defaults for MIMEApplication:

payload = MIMEApplication(attach_file.read(),
                'vnd.openxmlformats-officedocument.wordprocessingml.document')
payload.add_header('Content-Disposition',
                   "attachment; filename= %s" % attach_file)
message.attach(payload)

But I must acknowledge that this last point is mainly a matter of taste...

Upvotes: 1

Related Questions