I am working on a piece of code that regularly sends emails from 4 different accounts, 2 of them are gmail accounts and the other 2 are yahoo accounts. When I started writing the code I was able to send all the emails from both the gmail accounts using the following piece of code:
def sendGmail(self, fromaddr, toaddr, username, password,
email_body, email_subject
):
# Build the email
msg = MIMEText(email_body)
msg['Subject'] = email_subject
msg['From'] = fromaddr
msg['To'] = toaddr
try:
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddr, msg.as_string())
server.quit()
print "email sent: %s" % fromaddr
except Exception as e:
print "Something went wrong when sending the email %s" % fromaddr
print e
As I said, this piece of code worked perfectly, now that I add the sendYahoomail(), which is a different method, I always get (530, 'Access denied') as an exception for using sendGmail(). I'm pretty sure it's got nothing to do with my Yahoo method, and I can login from the browser with the gmail credentials correctly.
What can possibly be wrong, or just Gmail doesn't want me to send through code ?
I tried your code above with my Gmail account (actually it's a Google Apps account, but that should be identical) and it works fine for me. I even tried an incorrect "From" header and also using the incorrect source address at the SMTP level - both times Gmail allowed me to send the email, but seemed to quietly fix up the header on egress. Still, you might like to double-check your from address matches your username. Also try using the full email address as the username if you're currently just using the part before the @.
I also tried an incorrect password and received error 535, which isn't the same as what you're seeing. Since I have 2-factor authentication enabled I also tried my real password instead of an application-specific one and that still gave a 535 error (but with the message "application-specific password required").
Is it possible that your ISP has set up something that's intercepting SMTP connections to Gmail? Seems unlikely, although my ISP once blocked access to Gmail on port 587 although port 465 still worked. Perhaps you could try using smtplib.SMTP_SSL
on port 465 just in case and see if that gives you any more joy.
You could also try sending to addresses at different providers in case Gmail is rejecting the send for that reason (e.g. if the other provider has been got on to a spam blacklist, for example). Also, if it's possible your email looks like spam, try you code with a message subject and body that's close to an authentic email and see if that helps.
You might find this helpful: https://support.google.com/mail/answer/14257
Basically, Google has detected an attempt to sign in from a server that it considers unfamiliar, and has blocked it. The link above lets you attempt to unblock it.
Sometimes it has worked for me, and sometimes not.