【问题标题】:Empty message send with smtplib使用 smtplib 发送空消息
【发布时间】:2014-10-06 14:26:39
【问题描述】:

我不明白为什么我用我的代码发送空消息。 没有消息,没有主题。

我已经阅读了大量示例,但我总是遇到同样的问题。 我什至不明白为什么有时我们必须使用 .close() 或 .quit()

我终于迷路了,我需要你的光。 请参阅下面我的最后一个代码。

    ### SEND EMAIL ###
    sender = "registration@myserver.com"
    destination = user.email
    html = ''
    text = ''
    if country is 'USA':
        text = "your pin code:"+pin 
        html = """\
        <html>
            <head></head>
            <body>
                <p>
                    Hi!<br>
                    How are you?<br>
                    Here is the pin code you wanted: ""+pin""
                </p>
            </body>
        </html>
        """     
    if country is 'CAN':
        text = "ton code pin:"+pin
        html = """
        <html>
            <head></head>
            <body>
                <p>
                    Bonjour !<br>
                    Ici le code pin: ""+pin""
                </p>
            </body>
        </html>
        """ 

    try:
        msg = MIMEMultipart('alternative')
        if country is 'USA':
            msg['Subject'] = "Registration"
        if country is 'CAN':
            msg['Subject'] = "Inscription"
        msg['From'] = sender
        msg['To'] = destination
        part1 = MIMEText(text, 'plain', 'utf-8')
        part2 = MIMEText(html, 'html', 'utf-8')
        msg.attach(part1)
        msg.attach(part2)
        usernameEmail = 'registration@myserver.com'
        passwordEmail = '123456'
        conn = smtplib.SMTP('smtp.myserver.com')
        conn.set_debuglevel(True) # Debug
        conn.login(usernameEmail, passwordEmail)
        try:
            conn.sendmail(sender, destination, msg.as_string())
        finally:
            conn.quit()
    except SMTPException:
        msg = 'unable to mail'
        code = '503'
        return {
            "error": {
            "message": msg,
            "type": "myserverException",
            "code": code
            }
        }

【问题讨论】:

    标签: python-2.7 smtplib


    【解决方案1】:

    我敢打赌,您的国家/地区变量有问题。如果它以某种方式设置为“CAN”或“USA”以外的其他内容,则消息和主题将为空白。

    你可能想改成这样:

    # can country be lower case? try using .upper()
    if country is 'CAN':
        # defining subject, text, and html in one block means you won't need to edit 
        # multiple spots if your logic changes.
        subject = 'Inscription'
        # yada
    else: # handle all cases, including unknowns.
        subject = 'Registration'
    

    您可能还想处理conn.sendmail 的错误。

    【讨论】:

    • 啊,我是假人。你说的对。但我想知道何时使用 .close() 或 quit()
    猜你喜欢
    • 2017-04-02
    • 2012-08-01
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    相关资源
    最近更新 更多