Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 623
cool77 Avatar asked Jun 06 '17 08:06

cool77


People also ask

How do you send the body of an email in Python?

In this tutorial you'll learn how to:Set up a secure connection using SMTP_SSL() and .starttls() Use Python's built-in smtplib library to send basic emails. Send emails with HTML content and attachments using the email package. Send multiple personalized emails using a CSV file with contact data.

How do I use Smtplib in Python 3?

Python provides smtplib module, which defines an SMTP client session object that can be used to send mails to any Internet machine with an SMTP or ESMTP listener daemon. host − This is the host running your SMTP server. You can specifiy IP address of the host or a domain name like tutorialspoint.com.

What is Smtplib in Python?

The smtplib module defines an SMTP client session object that can be used to send mail to any internet machine with an SMTP or ESMTP listener daemon. For details of SMTP and ESMTP operation, consult RFC 821 (Simple Mail Transfer Protocol) and RFC 1869 (SMTP Service Extensions).

How do you add multiple recipients in Python?

sendmail() function. In short, to send to multiple recipients you should set the header to be a string of comma delimited email addresses. The sendmail() parameter to_addrs however should be a list of email addresses.


2 Answers

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')
like image 117
Matheus Candido Avatar answered Sep 19 '22 06:09

Matheus Candido


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()
like image 34
Rolf of Saxony Avatar answered Sep 18 '22 06:09

Rolf of Saxony