Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send an email with Gmail as provider using Python?

I am trying to send email (Gmail) using python, but I am getting following error.

Traceback (most recent call last):   File "emailSend.py", line 14, in <module>   server.login(username,password)   File "/usr/lib/python2.5/smtplib.py", line 554, in login   raise SMTPException("SMTP AUTH extension not supported by server.")   smtplib.SMTPException: SMTP AUTH extension not supported by server. 

The Python script is the following.

import smtplib fromaddr = '[email protected]' toaddrs  = '[email protected]' msg = 'Why,Oh why!' username = '[email protected]' password = 'pwd' server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username,password) server.sendmail(fromaddr, toaddrs, msg) server.quit() 
like image 265
mahoriR Avatar asked Apr 13 '12 19:04

mahoriR


People also ask

How do you send an email using Python code?

Set up a secure connection using SMTP_SSL() and . starttls() Use Python's built-in smtplib library to send basic emails. Send emails with HTML content and attachments using the email package.

Can I use Gmail as an SMTP server?

Use the Gmail SMTP serverIf you connect using SSL or TLS, you can send mail to anyone inside or outside of your organization using smtp.gmail.com as your server. This option requires you to authenticate with your Gmail or Google Workspace account and passwords.


1 Answers

def send_email(user, pwd, recipient, subject, body):     import smtplib      FROM = user     TO = recipient if isinstance(recipient, list) else [recipient]     SUBJECT = subject     TEXT = body      # Prepare actual message     message = """From: %s\nTo: %s\nSubject: %s\n\n%s     """ % (FROM, ", ".join(TO), SUBJECT, TEXT)     try:         server = smtplib.SMTP("smtp.gmail.com", 587)         server.ehlo()         server.starttls()         server.login(user, pwd)         server.sendmail(FROM, TO, message)         server.close()         print 'successfully sent the mail'     except:         print "failed to send mail" 

if you want to use Port 465 you have to create an SMTP_SSL object:

# SMTP_SSL Example server_ssl = smtplib.SMTP_SSL("smtp.gmail.com", 465) server_ssl.ehlo() # optional, called by login() server_ssl.login(gmail_user, gmail_pwd)   # ssl server doesn't support or need tls, so don't call server_ssl.starttls()  server_ssl.sendmail(FROM, TO, message) #server_ssl.quit() server_ssl.close() print 'successfully sent the mail' 
like image 185
David Okwii Avatar answered Sep 28 '22 10:09

David Okwii