smtplib and gmail - python script problems

I think that the GMail SMTP server does a reverse DNS lookup on the IP address that you connect from, and refuses the connection if no domain can be found. This is to avoid spammer from using their SMTP server as an open relay.


Some self-promotion here, but I feel on a valid ground.

You would literally only need this code to do exactly what you wrote:

import yagmail
yag = yagmail.SMTP('[email protected]')
yag.send('[email protected]', subject = None, contents = 'Hello')

Or a one liner:

yagmail.SMTP('[email protected]').send('[email protected]', None, 'Hello world.')

What is nice is that I propose to use keyring to store your password, so you never have a risk of people seeing your password in your script.

You can set this up by running once in your interpreter:

import yagmail
yagmail.register("[email protected]", "mypassword")

and exit. Then you can just use:

import yagmail
yagmail.SMTP("[email protected]") # without password

If you add .yagmail with "[email protected]" in your home dir, then you can just do: yagmail.SMTP(), but that's rather pointless by now.

Warning: If you get serious about sending a lot of messages, better set up OAuth2, yagmail can help with that.

yagmail.SMTP("[email protected]", oauth2_file="/path/to/save/creds.json")

The first time ran, it will guide you through the process of getting OAuth2 credentials and store them in the file so that next time you don't need to do anything with it. Do you suspect someone found your credentials? They'll have limited permissions, but you better invalidate their credentials through gmail.

For the package/installation please look at git or readthedocs, available for both Python 2 and 3.


Have you tried constructing a valid message?

from email.MIMEText import MIMEText

msg = MIMEText('body')
msg['Subject'] = 'subject'
msg['From'] = "..."
msg['Reply-to'] = "..."
msg['To'] = "..."

I don't know if OP still cares about this answer, but having found myself here in an effort to troubleshoot a similar problem, hopefully someone else might find this useful. As it turns out, Google has changed the way that they allow their SMTP server to be used. You will want to check a couple of things:

  1. That you are using the same address you used to authenticate as the 'from' address. If I am not mistaken it used to be the case that you could put pretty much whatever you wanted in the from field, but for security purposes many SMTP host sites (including google) now restrict this to the address that has authenticated with them.

  2. Allow your account to be accessed by 'less secure apps' (read: apps we do not generate revenue from). To do that log into your account and navigate here: https://www.google.com/settings/security/lesssecureapps

  3. Use port 587 with tls. Not really sure why but I could never get port 465 to play nice.

Hope this helps somebody else out.