简体   繁体   中英

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 = "my_sender@gmail.com"
    receiver_email = "my_receiver@x.y"
    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?

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 = "my_sender_address@gmail.com"
    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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM