-1

I'm trying to send an email within python, but the program is crashing when I run it either as a function in a larger program or on it's own in the interpreter.

import smtplib

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

fromaddr = "exampleg@gmail.com"
toaddr = "recipient@address.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Hi there"

body = "example"
msg.attach(MIMEText(body, 'plain'))

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "Password")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

In the interpreter, it seems to fail with server = smtplib.SMTP('smtp.gmail.com', 587)

Any ideas?

Adam Jarvis
  • 183
  • 1
  • 13

2 Answers2

0

My standard suggestion (as I'm the developer of it) is yagmail.

Install: pip install yagmail

Then:

import yagmail
yag = yagmail.SMTP(fromaddr, "pasword")
yag.send(toaddr, "Hi there", "example")

A lot of things can be made easier using the package, such as HTML email, adding attachments and avoiding having to write passwords in your script.

For the instructions to all of this (and more, sorry for the cliches), have a look at the readme on github.

PascalVKooten
  • 20,643
  • 17
  • 103
  • 160
0

That's because you are getting error when trying to connect Google SMTP server. Note that if you are using Google SMTP you should use:

Username: Your gmail address
Password: Your gmail password

And you should be already logged in. If you still get an error, you should check what is the problem in this list: https://stackoverflow.com/a/25238515/1600523

Note: You can also use your own SMTP server.

Community
  • 1
  • 1
skynyrd
  • 942
  • 4
  • 14
  • 34