Search code examples
pythonpython-2.7emailsmtpsmtplib

E-mail sent with smtplib ends as spam


I have the following code:

import smtplib, ssl


def send_email(temperature):
    port = 465  # For SSL
    password = "my_password"
    sender_email = "[email protected]"
    receiver_email = "[email protected]"
    message = """\
    Subject: Temperature is %0.2f degrees C

     """ % temperature

    server = smtplib.SMTP_SSL("smtp.gmail.com", port)
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)

if __name__ == "__main__":
    send_email(7.7)

After the first run, the first message was received OK. Next messages were in a spam folder without sender address, subject and body. I tried to mark it as not spam, but it didn't help. The message headers have the correct sender address, subject and body.

Can I correct it somehow?


Solution

  • I solved it as follows:

    import smtplib, ssl
    from email.mime.text import MIMEText
    
    def send_email(temperature):
        port = 465  # For SSL
        password = "my_password"
        sender_email = "[email protected]"
        receiver_email = "my_receiver_address.x.y"
        message = MIMEText("Temperature is %0.2f degrees" % temperature)
        message['Subject'] = "%0.2f degrees" % temperature
        message['From'] = sender_email
        message['To'] = receiver_email
    
        server = smtplib.SMTP_SSL("smtp.gmail.com", port)
        server.login(sender_email, password)
        server.sendmail(sender_email, [receiver_email], message.as_string())
        server.quit()
    
    if __name__ == "__main__":
        send_email(7.7)