代码之家  ›  专栏  ›  技术社区  ›  Kiwipo17

如何在python 3.6.2中向自动邮件(smtplib)添加更改内容?

  •  0
  • Kiwipo17  · 技术社区  · 7 年前

    我想给自己发封信。如何将内容更改为可变文本而不是静态文本?

    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?!'
    

    这就是部分 (body=...) 我想我有麻烦了。我怎样才能把“食物”从 random.choice() part并没有收到错误消息?还是有更好的方法?

    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()
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Nikhil Fadnis    7 年前

    通过向函数传递要使用的值。还要注意的是,函数定义应该在使用之前进行。

    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)