DEV Community

Manish Chaudhary
Manish Chaudhary

Posted on

4

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

    try:
        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)
        print(e)

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

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

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

Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs