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