How to save result of a function into a string so it can be sent via email (using smtplib and MIME)?
I am new to Python and very much a rookie. I am trying to write a program that uses the requests module to make a request to the Dark Sky API for a weather forecast, and then uses smtplib to send that forecast in an email to myself. I have truncated my code to only show the relevant parts. I have been unable to find any answers so far so I apologise if this is a duplicate. The below code will print the function to the console without any issues, but when I try to assign it to the "body" variable and email it, the email is blank. Or if I use str(ds.current)) the email just has "none" as the body text.
How can I make it work so that the body text of the email contains the forecast that has been requested from the API? Many thanks in advance, and sorry for any rookie errors.
import requests import json import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText class Darksky(): r = requests.get('https://api.darksky.net/forecast/e01635ccacb5548e3d1fa40403bbb3a5/-45.0312,168.6626?units=ca') wx_json = r.json() def __init__(self, source): self.source = source print "\n", "-" * 20, source, "-" * 20, "\n" def current(self): def summary(): return "CURRENT WEATHER:" x = self.wx_json['currently']['summary'] return x # I have tried using print instead of return but that did not work either. def temp(): return "TEMPERATURE:" y = self.wx_json['currently']['temperature'] return y summary() temp() ds = Darksky("DARKSKY WX") fromaddr = "firstname.lastname@example.org" toaddr = "email@example.com" msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "YOUR DAILY WEATHER, SIR." body = ds.current() # This is where I am trying to save the function result as a string that can be emailed. # I have tried using "str(ds.current())" but that just returns "none". print body msg.attach(MIMEText(body, 'plain')) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(fromaddr, "virtualbutler") text = msg.as_string() msg = "CAN YOU HEAR ME, SIR?" server.sendmail(fromaddr, toaddr, text) server.quit()