3
votes

I am developing an application using python where I need to send a file through mail. I wrote a program to send the mail but dont know there's something wrong. The code is posted below. Please any one help me with this smtp library. Is there's anything i m missing? And also can someone please tell me what will be the host in smtp! I am using smtp.gmail.com. Also can any one tell me how can i email a file (.csv file). Thanks for the 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"
1
Please provide the error details.Nilesh
Tichodroma, Lafada, : socket.error:[Errno 10060] A connectoin attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respondSujit Shakya

1 Answers

4
votes

You aren't logging in. There are also a couple reasons you might not make it through including blocking by your ISP, gmail bouncing you if it can't get a reverse DNS on you, etc.

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 your request to be able to attach a file. That changes things since now you need to deal with encoding. Still not that tough to follow though I don't think.

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