问题
I have quickly written below code to send data being sent to REST remote server for debuging but I am receiving blank email. now sure what is going wrong . in the terminal body dict text or json converted text is getting printed but getting nothing in email.
# For testing
def sendMail(usr, pwd, to, body):
""" just for testing to send error via email
"""
fromaddr = usr
toaddr = to
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Data add request"
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(usr, pwd)
msg.attach(body)
r = json.dumps(body)
loaded_r = json.loads(r)
print "json: ", str(loaded_r)
server.sendmail("error-report@do_not_reply.com", to, str(loaded_r))
except Exception, err:
print 'Error sending email: ', err
finally:
server.quit()
I tried sending server.sendmail("error-report@do_not_reply.com", to, body)
but that too sends blank email without subject. what am I doing wrong ?
回答1:
The message you pass as the third argument to sendmail
needs to be a valid, properly formatted RFC822 message. A JSON file is, by definition, not a valid email message.
def sendMail(usr, pwd, to, body):
msg = MIMEText(body)
msg['From'] = usr
msg['To'] = to
msg['Subject'] = "Data add request"
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(usr, pwd)
server.send_message("error-report@do_not_reply.com", [to], msg)
except Exception, err:
print 'Error sending email: ', err
finally:
server.quit()
I switched to send_message
here because it takes care of the minor mundane detail of converting the email.Message
object to a string object again before calling sendmail
.
It's not clear if you expect the body to be a text part displaying the contents of the string body
, or a JSON attachment containing body
as JSON, or perhaps both.
If you only need one body part, making the message multipart is obviously unnecessary. If you want multiple parts, then each of them should be a separate MIMEText
or some other MIME container type which you can msg.attach()
to a top-level MIMEMultipart
.
回答2:
I think it's the message : you should put for message
text = loaded_r.as_string()
And then you can send the mail .
server.sendmail("error-report@do_not_reply.com", to, text)
来源:https://stackoverflow.com/questions/55077603/getting-a-blank-email