How to get line breaks in e-mail sent using Python's smtplib?

前端 未结 5 1709
说谎
说谎 2020-12-01 15:36

I have written a script that writes a message to a text file and also sends it as an email. Everything goes well, except the email finally appears to be all in one line.

5条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 16:22

    You have your message body declared to have HTML content ("Content-Type: text/html"). The HTML code for line break is
    . You should either change your content type to text/plain or use the HTML markup for line breaks instead of plain \n as the latter gets ignored when rendering a HTML document.


    As a side note, also have a look at the email package. There are some classes that can simplify the definition of E-Mail messages for you (with examples).

    For example you could try (untested):

    import smtplib
    from email.mime.text import MIMEText
    
    # define content
    recipients = ["recipient_id@yahoo.com"]
    sender = "sender_id@gmail.com"
    subject = "report reminder"
    body = """
    Dear Student,
    Please send your report
    Thank you for your attention
    """
    
    # make up message
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = ", ".join(recipients)
    
    # sending
    session = smtplib.SMTP('smtp.gmail.com', 587)
    session.starttls()
    session.login(sender, 'my password')
    send_it = session.sendmail(sender, recipients, msg.as_string())
    session.quit()
    

提交回复
热议问题