Python – You can’t send emails using Python SMTP

You can’t send emails using Python SMTP… here is a solution to the problem.

You can’t send emails using Python SMTP

I’m developing an application using python and I need to send a file by mail. I wrote a program to send mail, but I don’t know what’s wrong. The code is pasted below. Please anyone help me with this smtp library. Is there anything I’m missing? Can anyone else tell me what a host in SMTP is! I’m using smtp.gmail.com.
Can someone also tell me how to email a file (.csv file). Thanks for your help!

#!/usr/bin/python

import smtplib

sender = '[email protected]'
receivers = ['[email protected]']

message = """From: From Person <[email protected]>
To: To Person <[email protected]>
Subject: SMTP e-mail test

This is a test e-mail message.
"""

try:
   smtpObj = smtplib. SMTP('smtp.gmail.com')
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"
except:
   print "Error: unable to send email"

Solution

You are not logged in. There are also some reasons why you might not be able to get through, including being blocked by your ISP, returning to you if gmail can’t give you reverse DNS, and so on.

try:
   smtpObj = smtplib. SMTP('smtp.gmail.com', 587) # or 465
   smtpObj.ehlo()
   smtpObj.starttls()
   smtpObj.login(account, password)
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"
except:
   print "Error: unable to send email"

I just noticed that you asked to be able to attach files. This changed things because now you need to deal with coding. Although I don’t think so, it’s still not that hard to follow.

import os
import email
import email.encoders
import email.mime.text
import smtplib

# message/email details
my_email = '[email protected]'
my_passw = 'asecret!'
recipients = ['[email protected]', '[email protected]']
subject = 'This is an email'
message = 'This is the body of the email.'
file_name = 'C:\\temp\\test.txt'

# build the message
msg = email. MIMEMultipart.MIMEMultipart()
msg['From'] = my_email
msg['To'] = ', '.join(recipients)
msg['Date'] = email. Utils.formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(email. MIMEText.MIMEText(message))

# build the attachment
att = email. MIMEBase.MIMEBase('application', 'octet-stream')
att.set_payload(open(file_name, 'rb').read())
email. Encoders.encode_base64(att)
att.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file_name))
msg.attach(att)

# send the message
srv = smtplib. SMTP('smtp.gmail.com', 587)
srv.ehlo()
srv.starttls()
srv.login(my_email, my_passw)
srv.sendmail(my_email, recipients, msg.as_string())

Related Problems and Solutions