how to send email attachement using python 2.7
Question: 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
    


Answer: 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](http://stackoverflow.com/q/23046140/289011).

[smtplib](https://docs.python.org/2/library/smtplib.html) connects to an
existing SMTP server. You can see it more like an Outlook Express. Outlook is
a client (or a [Mail User
Agent](http://en.wikipedia.org/wiki/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](http://en.wikipedia.org/wiki/Simple_Mail_Transfer_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](http://www.xeams.com/smtprelay.htm)) 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](http://i.stack.imgur.com/i4djv.png)

There's a lot of stuff you can do with the
[email](https://docs.python.org/2/library/email.html) 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](http://stackoverflow.com/questions/9541837/attach-a-txt-file-in-
python-smtplib), 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.

