Send Email Using Python

1437
3
Jump to solution
01-25-2024 11:49 AM
JoshBillings
Occasional Contributor II

Hello all,

I am trying to send an email after a script completes. The email successfully sends but the To, From, and Subject of the email are all blank. Additionally, the "To" email that gets put into the body of the email has commas after every letter.

Code I am using is below. Any ideas?

 

fromaddr: 'from@from.com'   #example only
toaddrs: 'test@email.com'  #example only
subject = 'SUBJECT TEXT'
mailtext = 'EMAIL BODY TEXT'
   
   
msg = """\
From: %s 
To: %s
Subject: %s 

%s
""" % (fromaddr, ", ".join(toaddrs), subject, mailtext)
      
server = smtplib.SMTP('111.111.111.111')  #sample IP

if "Connection information provided was for a non-administrative user" in msg:
     server.sendmail(fromaddr, toaddrs , msg)
else:
     server.sendmail(fromaddr, toaddrs, msg)

server.quit()

 

Tags (3)
0 Kudos
1 Solution

Accepted Solutions
JoshBillings
Occasional Contributor II

@Amir-Sarrafzadeh-Arasi @BlakeTerhune Thanks for the suggestions! 

I was able to resolve my issues by using code similar to @BlakeTerhune example.

 

 

import smtplib
from email.message import EmailMessage

fromaddr = 'from@email.com'
toaddrs = 'to@email.com'
subject = 'SUBJECT'
mailtext = 'EMAIL BODY TEXT'
  
msg=EmailMessage()
msg['Subject'] = subject
msg['From'] = fromaddr
msg['To'] = toaddrs  
msg.set_content(mailtext)  

server = smtplib.SMTP('111.111.111.111')
server.send_message(msg)
server.quit()

 

View solution in original post

0 Kudos
3 Replies
Amir-Sarrafzadeh-Arasi
Occasional Contributor

Hey Josh,

Some suggestions,

1) I could not see the port number, because usually the port number should be pass after the ip in the SMTP function.

2) toaddrs is a list of emails, try to pass directly a list without using join.

3) After SMTP method and before send mail use this line of code.

server.ehlo()

 

Please let me know if it worked.

Good luck

Amir Sarrafzadeh Arasi
0 Kudos
BlakeTerhune
MVP Regular Contributor

Here's the function I use for sending emails (Python 3).

def sendEmail(subject="", body_content="", to=[], cc=[], bcc=[], from_addr="somedefaultsender@domain.com"):
    """Send a plain text email.

    Required imports:
        from email.message import EmailMessage # for a text/plain email message
        import smtplib # for sending email

    :param str subject: Subject line of email.
    :param str body_content: Main message in the body of the email.
    :param list to: A list of email addresses as strings for sending the email to.
    :param list cc: A list of email addresses as strings for CC'ing the email.
    :param list bcc: A list of email addresses as strings for BCC'ing the email.
    :param str from_addr: The email address from which to send the email.
    :return: All email addresses that received the email (to, cc, bcc).
    :rtype: Dictionary
    """
    from email.message import EmailMessage
    import smtplib
    # Validate email recipient args
    for recipient in [to, cc, bcc]:
        if not isinstance(recipient, list):
            raise TypeError(f"Recipients (to, cc, bcc) must each be a list of strings; not {type(recipient)}")
    # Create email message object and content.
    msg = EmailMessage()
    msg.set_content(body_content)
    # Set recipients
    msg["Subject"] = subject
    msg["From"] = from_addr
    msg["To"] = ", ".join(to)
    msg["Cc"] = ", ".join(cc)
    msg["Bcc"] = ", ".join(bcc)
    # Send the message via our own SMTP server.
    with smtplib.SMTP("mymailserver.domain") as smtp:
        smtp.send_message(msg)
    # Confirmation messaging.
    recipients = {"to": to, "cc": cc, "bcc": bcc}
    print(f"sendEmail() successful for recipients {recipients}")
    return recipients
JoshBillings
Occasional Contributor II

@Amir-Sarrafzadeh-Arasi @BlakeTerhune Thanks for the suggestions! 

I was able to resolve my issues by using code similar to @BlakeTerhune example.

 

 

import smtplib
from email.message import EmailMessage

fromaddr = 'from@email.com'
toaddrs = 'to@email.com'
subject = 'SUBJECT'
mailtext = 'EMAIL BODY TEXT'
  
msg=EmailMessage()
msg['Subject'] = subject
msg['From'] = fromaddr
msg['To'] = toaddrs  
msg.set_content(mailtext)  

server = smtplib.SMTP('111.111.111.111')
server.send_message(msg)
server.quit()

 

0 Kudos