add sender's name in the from field of the email in python

26,965

Solution 1

This should work:

msg['From'] = "Your name <Your email>"

Example below:

import smtplib
from email.mime.text import MIMEText


def send_email(to=['[email protected]'],
               f_host='example.example.com',
               f_port=587,
               f_user='[email protected]',
               f_passwd='example-pass',
               subject='default subject',
               message='content message'):
    smtpserver = smtplib.SMTP(f_host, f_port)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(f_user, f_passwd)  # from email credential
    msg = MIMEText(message, 'html')
    msg['Subject'] = 'My custom Subject'
    msg['From'] = "Your name <Your email>"
    msg['To'] = ','.join(to)
    for t in to:
        smtpserver.sendmail(f_user, t, msg.as_string())  # you just need to add 
                                                         # this in for loop in 
                                                         # your code.
    smtpserver.close()
    print('Mail is sent successfully!!')

    cont = """
    <html>
    <head></head>
    <body>
    <p>Hi!<br>
      How are you?<br>
      Here is the <a href="http://www.google.com">link</a> you wanted.
    </p>
    </body>
    </html>
    """
    try:
        send_email(message=cont)
    except:
        print('Mail could not be sent')

Solution 2

Just tested the following code with gmx.com and it works fine. Although, whether you get the same mileage is a moot point.
I have replaced all references to my email service with gmail

#!/usr/bin/python

#from smtplib import SMTP # Standard connection
from smtplib import SMTP_SSL as SMTP #SSL connection
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

sender = '[email protected]'
receivers = ['[email protected]']


msg = MIMEMultipart()
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg['Subject'] = 'simple email via python test 1'
message = 'This is the body of the email line 1\nLine 2\nEnd'
msg.attach(MIMEText(message))

ServerConnect = False
try:
    smtp_server = SMTP('smtp.gmail.com','465')
    smtp_server.login('#name#@gmail.com', '#password#')
    ServerConnect = True
except SMTPHeloError as e:
    print "Server did not reply"
except SMTPAuthenticationError as e:
    print "Incorrect username/password combination"
except SMTPException as e:
    print "Authentication failed"

if ServerConnect == True:
    try:
        smtp_server.sendmail(sender, receivers, msg.as_string())
        print "Successfully sent email"
    except SMTPException as e:
        print "Error: unable to send email", e
    finally:
        smtp_server.close()
Share:
26,965
cool77
Author by

cool77

Updated on November 26, 2021

Comments

  • cool77
    cool77 over 2 years

    I am trying to send email with below code.

    import smtplib
    from email.mime.text import MIMEText
    
    sender = '[email protected]'
    
    def mail_me(cont, receiver):
        msg = MIMEText(cont, 'html')
        recipients = ",".join(receiver)
        msg['Subject'] = 'Test-email'
        msg['From'] = "XYZ ABC"
        msg['To'] = recipients
        # Send the message via our own SMTP server.
        try:
            s = smtplib.SMTP('localhost')
            s.sendmail(sender, receiver, msg.as_string())
            print "Successfully sent email"
        except SMTPException:
            print "Error: unable to send email"
        finally:
            s.quit()
    
    
    cont = """\
       <html>
         <head></head>
         <body>
           <p>Hi!<br>
              How are you?<br>
              Here is the <a href="http://www.google.com">link</a> you wanted.
           </p>
         </body>
       </html>
       """
    mail_me(cont,['xyz@xyzcom'])
    

    I want "XYZ ABC" to appear as the sender's name when the email is received and its email address as '[email protected]'. but when i receive email i am receiving weird details in "from" fields of the email message.

    [![from:    XYZ@<machine-hostname-appearing-here>
    reply-to:   XYZ@<machine-hostname-appearing-here>,
    ABC@<machine-hostname-appearing-here>][1]][1]
    

    I have attached a screenshot of the email that i receive.

    how can i fix this according to my need.

    • Gahan
      Gahan almost 7 years
      have you successfully configured your own smtp server?
  • cool77
    cool77 almost 7 years
    nope. that din't solve the issue. more over smtplib accepts recepient's email address as a list. so cannot replace it as a string
  • cool77
    cool77 almost 7 years
    yes. if you see the code, i have used "From" in the header. msg['From'] = "XYZ ABC"
  • Arian Acosta
    Arian Acosta over 6 years
    Welcome to Stack Overflow! In general, it is preferable to provide an answer with an explanation, and maybe a full example.
  • noamyg
    noamyg almost 5 years
    Works great! thanks. However, I noticed that some email clients (older outlooks for instance) would show the <[email protected]> in the inbox as sender. I think that the proper way to do it would be to import from email.header import Header and from email.utils import formataddr and do: msg['From'] = formataddr((str(Header('Your name', 'utf-8')), '[email protected]')).
  • Admin
    Admin over 4 years
    Just want to add new case. It never passes when I used text like this "Company Name CO., LTD <email>". But it'll work when I write "(Company Name CO., LTD) <email>". python 3.7
  • luke
    luke about 4 years
    The for loop is unnecessary here. Based on the official documentation, the 2nd parameter of sendmail function is a list of RFC 822 to-address strings (a bare string will be treated as a list with 1 address). We can just use smtpserver.sendmail(f_user, to, msg.as_string()) instead for code simplicity.
  • luke
    luke about 4 years
    Also, if you would like to follow the original code example, the indentation of smtpserver.close() line should be removed in order to be able to send to multiple email addresses.
  • xaif
    xaif over 3 years
    This code is sending emails but I have a problem, My google account name is TheGreatKings but this sends email as thegreatkings i.e. without camel case. Any solution ???
  • fazistinho_
    fazistinho_ over 3 years
    @noamyg I've tried your strategy on the msg['From'] field as per the above, the name appears great, but the email always shows up as the Gmail address. What should the [email protected] bit be doing?
  • noamyg
    noamyg over 3 years
    @HiFizzle_ please see if this post helps you: stackoverflow.com/a/56101240/3367818.