DEV Community

Manish Chaudhary
Manish Chaudhary

Posted on

How to add Sender Name when sending email using python

from email.mime.text import MIMEText
import smtplib

def send_email(server, recipient, subject, body, sender_name, sender_email):
    msg = MIMEText(body, 'html')
    msg['Subject'] = subject
    msg['From'] = f"{sender_name} <{sender}>"
    msg['To'] = recipient
    msg['X-Mailer'] = f"{sender_name}"

        server.sendmail(sender, recipient, msg.as_string())
        print("Email sent to sender: " + recipient)
    except Exception as e:
        print("Email failed to send to sender: " + recipient)

smtp_host = 'smtp service host'
smtp_port = port
smtp_username = 'username'
smtp_password = 'pasword'

server = smtplib.SMTP(smtp_host, smtp_port)
server.login(smtp_username, smtp_password)
recipient = ""
subject = "Test Email"
body = "This is a test email"
sender = ""

send_email(server, recipient, subject, body, sender_name, sender_email)

Enter fullscreen mode Exit fullscreen mode

Top comments (0)