yohowi
yohowi

Reputation: 41

send email using python using Gmail

I have written a python script to send email from my gmail account to my another email. the code is:

import smtplib
fromaddr = '[email protected]'
toaddrs  = '[email protected]'

msg = 'my message'

username = '[email protected]'
password = 'myPass'

server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
print("Done")

I'm also getting the "Done" output as the email is being sent. But the problem is: I can't seem to receive the email. It doesn't show up in the inbox. I can't find the problem :( Can anyone please help?

Thanks in advance...

Upvotes: 2

Views: 5893

Answers (2)

Pedro Lobito
Pedro Lobito

Reputation: 99081

Enable less secure apps on your gmail account and for Python3 use:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

gmailUser = '[email protected]'
gmailPassword = 'XXXXX'
recipient = '[email protected]'

message = f"""
Your message here...
"""

msg = MIMEMultipart()
msg['From'] = f'"Your Name" <{gmailUser}>'
msg['To'] = recipient
msg['Subject'] = "Your Subject..."
msg.attach(MIMEText(message))

try:
    mailServer = smtplib.SMTP('smtp.gmail.com', 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(gmailUser, gmailPassword)
    mailServer.sendmail(gmailUser, recipient, msg.as_string())
    mailServer.close()
    print ('Email sent!')
except:
    print ('Something went wrong...')

Upvotes: 0

Moolshanker Kothari
Moolshanker Kothari

Reputation: 551

Check this out, this works for me perfectly...

def send_mail(self):
    import smtplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEText import MIMEText

    gmailUser = '[email protected]'
    gmailPassword = 'P@ssw0rd'
    recipient = '[email protected]'
    message='your message here '

    msg = MIMEMultipart()
    msg['From'] = gmailUser
    msg['To'] = recipient
    msg['Subject'] = "Subject of the email"
    msg.attach(MIMEText(message))

    mailServer = smtplib.SMTP('smtp.gmail.com', 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(gmailUser, gmailPassword)
    mailServer.sendmail(gmailUser, recipient, msg.as_string())
    mailServer.close()

Upvotes: 4

Related Questions