user20212761
user20212761

Reputation:

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

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.

Upvotes: -1

Views: 957

Answers (2)

Bob S.
Bob S.

Reputation: 1

Without mimetext, format your message like this:

message = ("Subject: Test Email\n\n"
           "This is the body of a test email message.")
connection.sendmail(from_addr=sender,to_addrs=receiver, msg=message)

Upvotes: 0

Bijay Regmi
Bijay Regmi

Reputation: 1288

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")

Upvotes: 1

Related Questions