5

i have tried below code to send attachment, but file is not sending , only content is sending. please help.

SERVER = "smtp.example.com" FROM = "[email protected]" TO = ["listOfEmails"] # must be a list enter code here SUBJECT = "Subject" TEXT = "Your Text" # Prepare actual message message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\ %s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) DNSFile="abc.csv" # Send the mail import smtplib msg = MIMEMultipart() msg.attach(DNSFile) server = smtplib.SMTP(SERVER) server.sendmail(FROM, TO, message) server.quit()## Heading ## 

2 Answers 2

7

The code I use is to send attachments using Python is:

import smtplib from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email import encoders ## FILE TO SEND AND ITS PATH filename = 'some_file.csv' SourcePathName = 'C:/reports/' + filename msg = MIMEMultipart() msg['From'] = '[email protected]' msg['To'] = '[email protected]' msg['Subject'] = 'Report Update' body = 'Body of the message goes in here' msg.attach(MIMEText(body, 'plain')) ## ATTACHMENT PART OF THE CODE IS HERE attachment = open(SourcePathName, 'rb') part = MIMEBase('application', "octet-stream") part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % filename) msg.attach(part) server = smtplib.SMTP('smtp.office365.com', 587) ### put your relevant SMTP here server.ehlo() server.starttls() server.ehlo() server.login('[email protected]', 'password_here') ### if applicable server.send_message(msg) server.quit() 

Hope this works for you. This works for me like a charm.

Sign up to request clarification or add additional context in comments.

1 Comment

I changed SMTP server to imap-mail.outlook.com, also created an "app password" because I had two step verification enabled. Then this script works like a charm.
4

In case anyone else finds themselves here in 2022; Here are the Updated IMAP, POP, and SMTP Settings for Outlook.com:

  • IMAP Server Name: outlook.office365.com
  • IMAP Port: 993
  • IMAP Encryption Method: TLS
  • POP Server Name: outlook.office365.com
  • POP Port: 995
  • POP Encryption Method: TLS
  • SMTP Server Name: smtp-mail.outlook.com
  • SMTP Port: 587
  • SMTP Encryption Method: STARTTLS

Source

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.