0

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()
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
Kiwipo17
  • 23
  • 4

1 Answers1

0

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)
Nikhil Fadnis
  • 787
  • 5
  • 14
  • thank you for your answer! But python still complains like this: AttributeError: 'dict' object has no attribute 'encode' – Kiwipo17 Dec 08 '17 at 20:06
  • Can you post the stack trace please, would be helpful – Nikhil Fadnis Dec 08 '17 at 20:10
  • Traceback (most recent call last): File "/Users/me/Documents/rezepte.py", line 42, in mail(food) File "/Users/me/Documents/rezepte.py", line 21, in mail msg.attach(MIMEText(body,'plain')) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/email/mime/text.py", line 34, in __init__ _text.encode('us-ascii') AttributeError: 'dict' object has no attribute 'encode' – Kiwipo17 Dec 08 '17 at 20:18
  • Can you try changing this : `body = MIMEText(food) msg.attach(body)` with msg.attach on the new line – Nikhil Fadnis Dec 08 '17 at 20:36