Search code examples
smtplib

no email sent with smtplib localhost


I am using following code to send an email

python -m smtpd -n -c DebuggingServer localhost:1025

then on the console from (https://docs.python.org/2/library/email-examples.html):

Import smtplib for the actual sending function

import smtplib

# Import the email modules we'll need
from email.mime.text import MIMEText

# Open a plain text file for reading.  For this example, assume that
# the text file contains only ASCII characters.

textfile = 'sample_email.txt'

fp = open(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()

me = 'william@gmail.com'
you = 'william@mydomain.io'
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server, but don't include the
# envelope header.
SERVER = 'localhost'

s = smtplib.SMTP(SERVER, 1025)

s.sendmail(me, [you], msg.as_string())
s.quit()

I can see the following on the terminal

---------- MESSAGE FOLLOWS ----------
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Subject: The contents of sample_email.txt
From: william@gmail.com
To: william@mydomain.io
X-Peer: 127.0.0.1

this is a simple text message

------------ END MESSAGE ------------

and yet I receive no email on william@mydomain.io --> nothing on the spam folder either.

In case it helps, the server on which I am running the code is a AWS instance.


Solution

  • this happens because aws does not allow sending out email from 'localhost'. You need to use a specific AWS email server. More info over https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-smtp.html.

    This is done presumably to restrict the use of illegal email sending from AWS servers.