2

I am getting error when using this code to send email using localhost ip, any suggestion how to solve the socket error?

def SendTMail(self):
# Import the email modules we'll need

# Open a plain text file for reading.  For this example, assume that
# the text file contains only ASCII characters.
#try:
    fp = open('testint.txt', 'rb')
    # Create a text/plain message
    msg = MIMEText(fp.read())
    testfile = 'TESTING REPORT'
    fp.close()

    me = '124@hotmail.co.uk'
    you = '123@live.com'
    msg['Subject'] = 'The contents of %s' % testfile
    msg['From'] = me
    msg['To'] = you

    # Send the message via our own SMTP server, but don't include the
    # envelope header.
    s = smtplib.SMTP('192.168.1.3')
    s.sendmail(me, [you], msg.as_string())
    s.quit()     

the error is shown below:

File "x:\example.py", line 6, in SendTMail s = smtplib.SMTP('192.168.1.3') 
File "x:\Python27\lib\smtplib.py", line 251, in init (code, msg) = self.connect(host, port)
File "x:\Python27\lib\smtplib.py", line 311, in connect self.sock = self._get_socket(host, port, self.timeout)
File "x:\Python27\lib\smtplib.py", line 286, in _get_socket return socket.create_connection((host, port), timeout)
File "x:\Python27\lib\socket.py", line 571, in create_connection raise err – 
error: [Errno 10051] A socket operation was attempted to an unreachable network
Savir
  • 17,568
  • 15
  • 82
  • 136
  • could you please post the error too? – Savir Apr 13 '14 at 17:51
  • Do you have an SMTP server in your computer? – Savir Apr 13 '14 at 17:52
  • error: [Errno 10051] A socket operation was attempted to an unreachable network this the error – user3395021 Apr 13 '14 at 17:53
  • Well, I don't have an SMTP SERVER i'M TRYING TO SEND IT from my local network(home) – user3395021 Apr 13 '14 at 17:54
  • But smtplib.SMTP connects to an **existing** SMTP server to send the email. You need to install (nd configure) one first – Savir Apr 13 '14 at 17:56
  • File "x:\example.py", line 6, in SendTMail s = smtplib.SMTP('192.168.1.3') File "x:\Python27\lib\smtplib.py", line 251, in __init__ (code, msg) = self.connect(host, port) File "x:\Python27\lib\smtplib.py", line 311, in connect self.sock = self._get_socket(host, port, self.timeout) File "x:\Python27\lib\smtplib.py", line 286, in _get_socket return socket.create_connection((host, port), timeout) File "x:\Python27\lib\socket.py", line 571, in create_connection raise err – user3395021 Apr 13 '14 at 17:58
  • Ok, that `socket.create_connection((host, port)` is the thing trying to connect to the existing SMTP server at `192.168.1.3`, which doesn't exist, and therefore it's blowing up... I'm pretty sure I can post how to send an email using the Gmail SMTP server, but that's not what you want, right? – Savir Apr 13 '14 at 18:01
  • well I want to connect to a public server hotmail. if you post it will also probably work for hotmail? – user3395021 Apr 13 '14 at 18:07
  • I'm not sure about hotmail's situation now, but I can try (I have a hotmail account as well **;-)** – Savir Apr 13 '14 at 18:12
  • ok i will try the gmail too then – user3395021 Apr 13 '14 at 18:49

1 Answers1

2

Before posting raw code, I'd like to add an small explanation as per the conversation that took place in the comments to your question.

smtplib connects to an existing SMTP server. You can see it more like an Outlook Express. Outlook is a client (or a Mail User Agent, if you wanna get fancy). It doesn't send emails by itself. It connects to whatever SMTP server it has configured among its accounts and tells that server "Hey, I'm user xxx@hotmail.com (and here's my password to prove it). Could you send this for me?"

If you wanted to, having your own SMTP server is doable (for instance, in Linux, an easily configurable SMTP server would be Postfix, and I'm sure there are many for Windows) Once you set one up, it'll start listening for incoming connections in its port 25 (usually) and, if whatever bytes come through that port follow the SMTP protocol, it'll send it to its destination. IMHO, this isn't such a great idea (nowadays). The reason is that now, every (decent) email provider will consider emails coming from unverified SMTP servers as spam. If you want to send emails, is much better relying in a well known SMTP server (such as the one at smtp.live.com, the ones hotmail uses), authenticate against it with your username and password, and send your email relying (as in SMTP Relay) on it.

So this said, here's some code that sends an HTML text with an attachment borrajax.jpeg to an email account relying on smtp.live.com.

You'll need to edit the code below to set your hotmail's password (maybe your hotmail's username as well, if it's not 124@hotmail.co.uk as shown in your question) and email recipients. I removed mines from the code after my tests for obvious security reasons... for me :-D and I put back the ones I saw in your question. Also, this scripts assumes it'll find a .jpeg picture called borrajax.jpeg in the same directory where the Python script is being run:

import smtplib
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_mail():
    test_str="This is a test"
    me="124@hotmail.co.uk"
    me_password="XXX"   # Put YOUR hotmail password here
    you="123@live.com"
    msg = MIMEMultipart()
    msg['Subject'] = test_str
    msg['From'] = me
    msg['To'] = you
    msg.preamble = test_str
    msg_txt = ("<html>"
                "<head></head>"
                "<body>"
                    "<h1>Yey!!</h1>"
                    "<p>%s</p>"
                "</body>"
            "</html>" % test_str)
    msg.attach(MIMEText(msg_txt, 'html'))
    with open("borrajax.jpeg") as f:
        msg.attach(MIMEImage(f.read()))
    smtp_conn = smtplib.SMTP("smtp.live.com", timeout=10)
    print "connection stablished"
    smtp_conn.starttls()
    smtp_conn.ehlo_or_helo_if_needed()
    smtp_conn.login(me, me_password)
    smtp_conn.sendmail(me, you, msg.as_string())
    smtp_conn.quit()

if __name__ == "__main__":
    send_mail()

When I run the example (as I said, I edited the recipient and the sender) it sent an email to a Gmail account using my (old) hotmail account. This is what I received in my Gmail:

Gmail screenshot

There's a lot of stuff you can do with the email Python module. Have fun!!

EDIT:

Gorramit!! Your comment about attaching a text file wouldn't let me relax!! :-D I had to see it myself. Following what was detailed in this question, I added some code to add a text file as an attachment.

msg_txt = ("<html>"
            "<head></head>"
            "<body>"
                "<h1>Yey!!</h1>"
                "<p>%s</p>"
            "</body>"
        "</html>" % test_str)
msg.attach(MIMEText(msg_txt, 'html'))
with open("borrajax.jpeg", "r") as f:
    msg.attach(MIMEImage(f.read()))
#
# Start new stuff
#
with open("foo.txt", "r") as f:
    txt_attachment = MIMEText(f.read())
    txt_attachment.add_header('Content-Disposition',
                              'attachment',
                               filename=f.name)
    msg.attach(txt_attachment)
#
# End new stuff
#
smtp_conn = smtplib.SMTP("smtp.live.com", timeout=10)
print "connection stablished"

And yep, it works... I have a foo.txt file in the same directory where the script is run and it sends it properly as an attachment.

Community
  • 1
  • 1
Savir
  • 17,568
  • 15
  • 82
  • 136
  • Thanks alot....iT WORKS. I'm trying to figure out now how to send a text file attachement. Thanks for you help ;) – user3395021 Apr 13 '14 at 22:08
  • @user3395021, For a text attachment, check this out: http://stackoverflow.com/questions/9541837/attach-a-txt-file-in-python-smtplib **:-)** (I haven't tested it, but it should work) Oh, and glad I helped. – Savir Apr 13 '14 at 22:13
  • Just added the how to attach a .txt after verifying it works. Don't ask how to attach a PDF now!... I wanna be able to watch a movie!! Haha... (kiddin') have fun coding! **:-)** – Savir Apr 13 '14 at 22:24
  • lol dude it works when sending as plaintext, but as attachement I guess i need some sort of encoder heheh..Im getting there..:P – user3395021 Apr 13 '14 at 22:38
  • That's weird... Did you see my edit to my answer (by the end of it)? I get the file on my Gmail as an attachment. – Savir Apr 13 '14 at 22:41
  • I did not but it works now. you do have less code than what I have tested ;) Thanks again :) – user3395021 Apr 13 '14 at 22:54
  • I will test yours and see the difference ;) Enjoy your Movie by now ;) (kidding) – user3395021 Apr 13 '14 at 22:54