How to send email with smtplib and MIMEText?
Question
I'm looking for an answer for some days and untill now I just didn't solve my problem. All I want is to send a simple email message from my program if an error occure. I'm using the gmail server to do that, and it actually sends the email, but the message of the email doesn't appear. Here's the code:
def accept(self):
HOST = 'smtp.gmail.com'
PORT = '587'
user = '***********@gmail.com'
senha = '***********'
servidor = smtplib.SMTP()
servidor.connect(HOST, PORT)
servidor.ehlo()
servidor.starttls()
servidor.ehlo()
servidor.login(user, senha)
assunto = 'Relatorio de Erro'
para = '**************@hotmail.com'
endereco = self.nemail.text()
de = str(endereco)
texto = self.message.toPlainText()
textos = Message(texto)
corpo = MIMEText(textos)
corpo['From'] = de
corpo['To'] = user
corpo['Subject'] = assunto
servidor.set_debuglevel(1)
servidor.sendmail(user, para, corpo.as_string())
servidor.quit
This raises an error on the MIMEText. Says that can't convert MIMEText to str. The I tried another version, just for test. Sending a simple string:
def accept(self):
HOST = 'smtp.gmail.com'
PORT = '587'
user = '*************@gmail.com'
senha = '************'
servidor = smtplib.SMTP()
servidor.connect(HOST, PORT)
servidor.ehlo()
servidor.starttls()
servidor.ehlo()
servidor.login(user, senha)
assunto = 'Relatorio de Erro'
para = '*********@hotmail.com'
servidor.set_debuglevel(1)
servidor.sendmail(user, para, assunto)
servidor.quit()
The email comes to the right inbox, but it has no message, nothing. I searched a lot, I'd read the docs, I tried it so much that I don't even know what I'm doing. It looks like I'm almost getting. Can someone help me?
Solution
Here is a working version modified from code I use when we do system maintenance.
#!/usr/bin/env python
import smtplib
host = 'smtp.gmail.com'
port = '587'
user = 'user@gmail.com'
passw = 'password'
server = smtplib.SMTP()
server.connect(host, port)
server.ehlo()
server.starttls()
server.login(user, passw)
notice = "Completed"
tolist = ["user@somewhere.com"]
fromaddr = '"IT Staff" '
subject = 'Oracle server maintenance notice'
message = '''
The Oracle database server maintenance is
%s
''' % notice
hdr = "From: %s\r\nTo: %s\r\nSubject: %s\r\nX-Mailer: My-Mail\r\n\r\n" % (fromaddr, tolist, subject)
server.sendmail("it@vlsmaps.com", tolist, hdr+message)
server.quit