Search code examples
pythonpython-3.xemailsmtpsmtplib

How can I add changing content to an automated mail (smtplib) in python 3.6.2?


I want to send a mail to myself. How can I change the content to a varying text rather than a static text?

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

#food dictionary 

food = random.choice([spaghetti, pizza])

def mail():

    email_user = 'me'
    email_send = ['no1','no2']

    msg = MIMEMultipart()
    msg['From'] = email_user
    msg['To'] = ','.join(email_send)
    msg['Subject'] = 'food for the week!'

    body = 'why can't I get my new content in here?!'

this is the part (body=...) that I have troubles with I think. How can I put 'food' in there from the random.choice() part and not get an error message? Or is there a better way altogether?

msg.attach(MIMEText(body,'plain'))
text = msg.as_string()
mail =smtplib.SMTP("smtp.gmail.com", 587)
mail.ehlo()
mail.starttls()
mail.login(email_user,"pwd")
mail.sendmail(email_user,email_send, text)
mail.close()
mail()

Solution

  • By passing the function a value to be used. Also note, function definition should be before they are used.

    import smtplib
    import random
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    
    
    def mail(food):
    
        email_user = 'me'
        email_send = ['no1','no2']
    
        msg = MIMEMultipart()
        msg['From'] = email_user
        msg['To'] = ','.join(email_send)
        msg['Subject'] = 'food for the week!'
    
        body = food
        msg.attach(MIMEText(body,'plain'))
    
        text = msg.as_string()
    
        mail =smtplib.SMTP("smtp.gmail.com", 587)
    
        mail.ehlo()
    
        mail.starttls()
    
        mail.login(email_user,"pwd")
    
        mail.sendmail(email_user,email_send, text)
    
        mail.close()
    
        mail()
    #food dictionary 
    
    food = random.choice([spaghetti, pizza])
    mail(food)