Home > Net >  How can I add a Subject to my email to send via SMTP?
How can I add a Subject to my email to send via SMTP?

Time:11-30

How can I add a subject in it like I did in a normal message? When I am trying to send an email with the code below, it is showing with no Subject:

import smtplib, ssl

email = "fromemailhere"
password = "passwordhere"
receiver = "toemailhere"

message = """
Hello World
"""

port = 465
sslcontext = ssl.create_default_context()
connection = smtplib.SMTP_SSL(
    "smtp.gmail.com",
    port,
    context=sslcontext
)

connection.login(email, password)
connection.sendmail(email, receiver, message)

print("sent")

I have seen this example, but I don't understand how can I do this in my project. Can anyone tell me with a code example?

I am not a Python developer, but I want to use this program.

CodePudding user response:

It is fairly straight forward. Use email library (documentation). AFAIK it is a standard built in library, so no additional installation required. Your could would look like this:

import smtplib, ssl
from email.mime.text import MIMEText

email = "fromemailhere"
password = "passwordhere"
receiver = "toemailhere"

message = """
Hello World
"""
message = MIMEText(message, "plain")
message["Subject"] = "Hello World"
message["From"] = email

port = 465
sslcontext = ssl.create_default_context()
connection = smtplib.SMTP_SSL(
    "smtp.gmail.com",
    port,
    context=sslcontext
)

connection.login(email, password)
connection.sendmail(email, receiver, message.as_string())

print("sent")
  • Related