How to save result of a function into a string so it can be sent via email (using smtplib and MIME)?

Question

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 = "watsonthevirtualbutler@gmail.com"
    toaddr = "matt@peakpixel.nz"

    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()

Show source
| email   | python-2.7   | python-requests   | mime-types   | smtplib   2016-12-13 01:12 1 Answers

Answers to How to save result of a function into a string so it can be sent via email (using smtplib and MIME)? ( 1 )

  1. 2016-12-13 10:12

    Your summary() and temp() has two return operators, while only one return is acceptable. If you want your_function() to return few values, you can do something like: return {"first_parameter": "first_value", "second_parameter": "second_value"} and then call each value as your_function()["first_parameter"] or your_function()["second_parameter"]

    Try following code and let me know the result:

    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):
            return "CURRENT WEATHER: {0}. TEMPERATURE: {1}".format(self.wx_json['currently']['summary'], self.wx_json['currently']['temperature'])
    
    
    ds = Darksky("DARKSKY WX")
    body = ds.current()
    

Leave a reply to - How to save result of a function into a string so it can be sent via email (using smtplib and MIME)?

◀ Go back