用smtplib发送空消息

时间:2014-10-06 14:26:40

标签: python-2.7 smtplib

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

我已经阅读了大量样本,但我总是遇到同样的问题。 我甚至不明白为什么有时候我们必须使用.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
            }
        }

1 个答案:

答案 0 :(得分:1)

我敢打赌,您的国家/地区变量存在问题。如果以某种方式设置为&#34; CAN&#34;或&#34;美国&#34;然后消息和主题将是空白的。

您可能希望将其结构化为:

# 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的错误。