2

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...

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
yohowi
  • 41
  • 1
  • 2

2 Answers2

4

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()
  • 1
    Should be `from email.mime.multipart import MIMEMultipart` & `from email.mime.text import MIMEText` and the self parameter is superfluous – Zander Brown Jul 17 '17 at 16:53
0

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...')
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268