首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据我是按语句还是按块运行代码语句,我怎么可能得到不同的结果呢?

根据我是按语句还是按块运行代码语句,我怎么可能得到不同的结果呢?
EN

Stack Overflow用户
提问于 2019-03-07 23:06:16
回答 1查看 47关注 0票数 2

我有一个代码,用于在符合条件时发送电子邮件:

代码语言:javascript
复制
import datetime
import smtplib

today = datetime.date.today()
email_date = today
items = [1, 2]
gmail_email = "put_your_email_here"
password = "put your password here"

if email_date == today:
    # send email
    sent_from = gmail_email
    sent_to = ['email_1', 'email_2']
    sent_subject = 'Subject of the email'
    sent_body = ("""Hello,

    This is part of a reproducible code

    Kind regards""")

    email_text = """\
    From: %s
    To: %s
    Subject: %s

    %s
    """ % (sent_from, ', '.join(sent_to), sent_subject, sent_body)

    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(gmail_email, password)
    server.sendmail(sent_from, sent_to, email_text)
    server.close()

但是,如果我运行整个代码,发送的电子邮件的主题和正文都是空的,所有内容都放在电子邮件的"from“中。

如果我一条接一条地运行语句(从条件语句之后开始),我会正确地收到电子邮件。这里我漏掉了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-07 23:15:42

这可能与您将文本块分配给email_text变量的方式有关。文本是缩进的,而电子邮件的标题字段应该在行的开头。尝试将其更改为:

代码语言:javascript
复制
        email_text = """\
From: %s
To: %s
Subject: %s

%s
""" %(sent_from, ', '.join(sent_to), sent_subject, sent_body)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55046952

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档