Search code examples
pythonpython-3.xsmtplib

Python Smtplib, how to set a subject


Ok, I'm trying to send a email with smtplib with the code which is working! But I don't know how to put a subject in, I've seen some other people here talk about it but the method they used made it so you couldn't put any text in so I'm asking here.

also, the sender is a gmail account and same as the receiver.

import smtplib
import socket

email='xxxxxxxxxx'
password='xxxxxxxxxx'
    
    
def sendMail(to, subject, message):
    try:
        server = smtplib.SMTP('smtp.gmail.com', 587)
        print("Connection Status: Connected")
    except socket.gaierror:
        print("Connection Status: ERROR: Not connected to the internet")
    server.ehlo()
    server.starttls()
    server.login(email, password)
    # subject here or something
    server.sendmail('text', to, message)
    
try:
    sendMail('xxxxxxxx', 'this is the text')
except smtplib.SMTPAuthenticationError:
    print("ERROR: Username or Password are not accepted")

Solution

  • import smtplib
    import socket
    
    
    message = f'Subject: {SUBJECT}\n\n{TEXT}'
    server = smtplib.SMTP(SERVER)
    server.sendmail(FROM, TO, message)
    server.quit()