2014-10-06 89 views
0

我不明白爲什麼我用我的代碼發送空信息。 沒有信息,沒有主題。用smtplib發送空信息

我讀過大量的樣本,但我總是有同樣的問題。 我甚至不明白爲什麼有時我們必須使用.close()或.quit()

最後我迷路了,我需要你的光。 看下面我的最後一個代碼。

### SEND EMAIL ### 
    sender = "[email protected]" 
    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 = '[email protected]' 
     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

我敢打賭,你的國家變量有問題。如果它以某種方式設置爲「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

+0

啊,我是假的。你是對的。但是我想知道什麼時候使用.close()或者quit() – OlZ 2014-10-06 14:51:39