TAGS :Viewed: 7 - Published at: a few seconds ago

[ How to send an email to corporate email account using Python? ]

I have a corporate email account. Now I need to send out an email to a corporate email account within our company using Python. We use Microsoft Exchange within our company along with Outlook.

I tried using the below code but it doesn't work for me and I always get SOCKET error

#!/usr/bin/python

import smtplib
from smtplib import SMTPException

message = """From: david@company.com
To: ron@company.com
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test

This is an e-mail message to be sent in HTML format

<b>This is HTML message.</b>
<h1>This is headline.</h1>
"""

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

Below is the error I am getting -

socket.error: [Errno 111] Connection refused

Here what should I replace for localhost or should I be using SMTP for this or some other thing?

Answer 1


localhost has to be replaced with smtp mail server address. Every corporate environment should have a smtp host. Any IT admin should be able to point you to it. It looks something similar to 'smtphost.corpabc.com'