Search code examples
python-2.7smtplib

Empty message send with smtplib


I don't understand why i send empty message with my code. No message, No subject.

I've read plenty of sample but i have always the same problem. I did not even understand why sometimes we have to use .close() or .quit()

Finally I'm lost, i need your light. See below my last code.

    ### 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
            }
        }

Solution

  • I will bet that you have a problem with your country variable. If it is somehow set to something other than "CAN" or "USA" then the message and the subject will be blank.

    You probably want to structure it something like this instead:

    # 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'
    

    You also may want to handle the error for conn.sendmail.