Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Subject header to server.sendmail() in Python

Tags:

python

email

smtp

I'm writing a python script to send emails from the terminal. In the mail which I currently send, it is without a subject. How do we add a subject to this email?

My current code:

    import smtplib

    msg = """From: [email protected]
    To: [email protected]\n
    Here's my message!\nIt is lovely!
    """

    server = smtplib.SMTP_SSL('smtp.example.com', port=465)
    server.set_debuglevel(1)
    server.ehlo
    server.login('examplelogin', 'examplepassword')
    server.sendmail('[email protected]', ['[email protected] '], msg)
    server.quit()
like image 224
user248884 Avatar asked Jun 06 '26 20:06

user248884


1 Answers

You need to put the subject in the header of the message.

Example -

import smtplib

msg = """From: [email protected]
To: [email protected]\n
Subject: <Subject goes here>\n
Here's my message!\nIt is lovely!
"""

server = smtplib.SMTP_SSL('smtp.example.com', port=465)
server.set_debuglevel(1)
server.ehlo
server.login('examplelogin', 'examplepassword')
server.sendmail('[email protected]', ['[email protected] '], msg)
server.quit()
like image 64
Anand S Kumar Avatar answered Jun 10 '26 07:06

Anand S Kumar