Search code examples
pythonemailgmailsmtplib

Display username in the mail sent from smtplib


I have written a python script to send mail using smtplib. Everything is working fine except, when the user receives the mail, he isn't able to see my google account name, instead he is getting the mail id. is there a way to make this right?

I guess it's got to do something here but am not sure.

msg = MIMEMultipart()

msg['From'] = from_addr
msg['To'] = ','.join(recipients_addr)
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
return msg

enter image description here

enter image description here

The first image is the one sent with smtplib. There is no username.

The second one is sent normally from gmail.


Solution

  • You need to provide both the email address and the account name to do this.

    The email.utils.formataddr function can be used to format the data:

    >>> from email import utils
    >>> utils.formataddr(('Jane Smith', '[email protected]'))
    'Jane Smith <[email protected]>'
    

    In the code the question, you would do something like

    from_addr = '[email protected]'
    from name = 'Praneeth Vasarla'
    msg['from'] = formataddr((from_name, from_addr))