Related
I am trying to send an email. The code I am using is found below:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
email_user = 'email#gmail.com'
email_password = 'password'
email_send = 'receiver#gmail.com'
subject = 'subject'
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject
body = 'Hi there, sending this email from Python!'
msg.attach(MIMEText(body,'plain'))
try:
text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com', port=587)
server.starttls()
server.login(email_user, email_password)
server.sendmail(email_user,email_send,text)
server.quit()
print('successfully sent the mail')
except:
print("failed to send mail")
I get an error "failed to send mail" with the error message:
SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials t10sm6451859wra.16 - gsmtp')
The error occurs on the server.login() line, I am not able to login.
I checked other post and it says, it has to do with wrong credentials but my credentials are correct. I have check and double checked.
What could be the problem with this and how do I resolve it?
Send an email using python is easy, you may have encountered mistakes in your snippet code above and I am lazy to debug your code. But here might be the code you prefer.
The smtp.gmail.com,465 make your code secure. This snippet of code will send email to recipient through spam but lot number of emails you wish to send, will not be blocked by Gmail, you also can use bot to send email through recipient via this snippet of code.
Send Multiple Recipients
In the to line, just separate recipients by comma
to = [
'<recipient_email_address1>',
'<recipient_email_address2>',
'<recipient_email_address3>']
import smtplib
def sendEmailFunc():
gmail_user = '<your_sender_email_address_here>'
gmail_password = '<credential_password_of_above_email>'
sent_from = gmail_user
to = ['<recipient_email_address>']
subject = '<write_your_email_subject_here>'
body = "<write_your_email_body_here>"
email_text = """
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, email_text)
server.close()
print ('====Email Sent Successfully====')
except:
print ('Something went wrong...')
NOTE
Please be careful with your indentation.
Hope this helpful for you.
Thank you.
After much searching I couldn't find out how to use smtplib.sendmail to send to multiple recipients. The problem was every time the mail would be sent the mail headers would appear to contain multiple addresses, but in fact only the first recipient would receive the email.
The problem seems to be that the email.Message module expects something different than the smtplib.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.
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import smtplib
msg = MIMEMultipart()
msg["Subject"] = "Example"
msg["From"] = "me#example.com"
msg["To"] = "malcom#example.com,reynolds#example.com,firefly#example.com"
msg["Cc"] = "serenity#example.com,inara#example.com"
body = MIMEText("example email body")
msg.attach(body)
smtp = smtplib.SMTP("mailhost.example.com", 25)
smtp.sendmail(msg["From"], msg["To"].split(",") + msg["Cc"].split(","), msg.as_string())
smtp.quit()
This really works, I spent a lot of time trying multiple variants.
import smtplib
from email.mime.text import MIMEText
s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = 'me#example.com'
recipients = ['john.doe#example.com', 'john.smith#example.co.uk']
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())
The msg['To'] needs to be a string:
msg['To'] = "a#b.com, b#b.com, c#b.com"
While the recipients in sendmail(sender, recipients, message) needs to be a list:
sendmail("a#a.com", ["a#b.com", "b#b.com", "c#b.com"], "Howdy")
You need to understand the difference between the visible address of an email, and the delivery.
msg["To"] is essentially what is printed on the letter. It doesn't actually have any effect. Except that your email client, just like the regular post officer, will assume that this is who you want to send the email to.
The actual delivery however can work quite different. So you can drop the email (or a copy) into the post box of someone completely different.
There are various reasons for this. For example forwarding. The To: header field doesn't change on forwarding, however the email is dropped into a different mailbox.
The smtp.sendmail command now takes care of the actual delivery. email.Message is the contents of the letter only, not the delivery.
In low-level SMTP, you need to give the receipients one-by-one, which is why a list of adresses (not including names!) is the sensible API.
For the header, it can also contain for example the name, e.g. To: First Last <email#addr.tld>, Other User <other#mail.tld>. Your code example therefore is not recommended, as it will fail delivering this mail, since just by splitting it on , you still not not have the valid adresses!
It works for me.
import smtplib
from email.mime.text import MIMEText
s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = 'me#example.com'
recipients = 'john.doe#example.com,john.smith#example.co.uk'
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = recipients
s.sendmail(sender, recipients.split(','), msg.as_string())
The solution below worked for me. It successfully sends an email to multiple recipients, including "CC" and "BCC."
toaddr = ['mailid_1','mailid_2']
cc = ['mailid_3','mailid_4']
bcc = ['mailid_5','mailid_6']
subject = 'Email from Python Code'
fromaddr = 'sender_mailid'
message = "\n !! Hello... !!"
msg['From'] = fromaddr
msg['To'] = ', '.join(toaddr)
msg['Cc'] = ', '.join(cc)
msg['Bcc'] = ', '.join(bcc)
msg['Subject'] = subject
s.sendmail(fromaddr, (toaddr+cc+bcc) , message)
So actually the problem is that SMTP.sendmail and email.MIMEText need two different things.
email.MIMEText sets up the "To:" header for the body of the e-mail. It is ONLY used for displaying a result to the human being at the other end, and like all e-mail headers, must be a single string. (Note that it does not actually have to have anything to do with the people who actually receive the message.)
SMTP.sendmail, on the other hand, sets up the "envelope" of the message for the SMTP protocol. It needs a Python list of strings, each of which has a single address.
So, what you need to do is COMBINE the two replies you received. Set msg['To'] to a single string, but pass the raw list to sendmail:
emails = ['a.com','b.com', 'c.com']
msg['To'] = ', '.join( emails )
....
s.sendmail( msg['From'], emails, msg.as_string())
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def sender(recipients):
body = 'Your email content here'
msg = MIMEMultipart()
msg['Subject'] = 'Email Subject'
msg['From'] = 'your.email#gmail.com'
msg['To'] = (', ').join(recipients.split(','))
msg.attach(MIMEText(body,'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('your.email#gmail.com', 'yourpassword')
server.send_message(msg)
server.quit()
if __name__ == '__main__':
sender('email_1#domain.com,email_2#domain.com')
It only worked for me with send_message function and using the join function in the list whith recipients, python 3.6.
I tried the below and it worked like a charm :)
rec_list = ['first#example.com', 'second#example.com']
rec = ', '.join(rec_list)
msg['To'] = rec
send_out = smtplib.SMTP('localhost')
send_out.sendmail(me, rec_list, msg.as_string())
I came up with this importable module function. It uses the gmail email server in this example. Its split into header and message so you can clearly see whats going on:
import smtplib
def send_alert(subject=""):
to = ['email#one.com', 'email2#another_email.com', 'a3rd#email.com']
gmail_user = 'me#gmail.com'
gmail_pwd = 'my_pass'
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + ", ".join(to) + '\n' + 'From: ' + gmail_user + '\n' + 'Subject: ' + subject + '\n'
msg = header + '\n' + subject + '\n\n'
smtpserver.sendmail(gmail_user, to, msg)
smtpserver.close()
I use python 3.6 and the following code works for me
email_send = 'xxxxx#xxx.xxx,xxxx#xxx.xxx'
server.sendmail(email_user,email_send.split(','),text)
I figured this out a few months back and blogged about it. The summary is:
If you want to use smtplib to send email to multiple recipients, use email.Message.add_header('To', eachRecipientAsString) to add them, and then when you invoke the sendmail method, use email.Message.get_all('To') send the message to all of them. Ditto for Cc and Bcc recipients.
Well, the method in this asnwer method did not work for me. I don't know, maybe this is a Python3 (I am using the 3.4 version) or gmail related issue, but after some tries, the solution that worked for me, was the line
s.send_message(msg)
instead of
s.sendmail(sender, recipients, msg.as_string())
This is an old question. My main reason to post a new answer is to explain how to solve the problem with the modern email library in Python 3.6+ and how it differs from the old version; but first, let's recap what Anony-Mousse wrote in their answer from 2012.
SMTP doesn't care at all what's in the headers. The list of recipients you pass in to the sendmail method are what actually determine where the message will be delivered.
In SMTP parlance, this is called the message's envelope. On the protocol level, you connect to the server, then tell it who the message is from (MAIL FROM: SMTP verb) and who to send it to (RCPT TO:), then separately transmit the message itself (DATA) with headers and body as one oblique string blob.
The modern smtplib simplifies the Python side of this by providing a send_message method which actually sends to the recipients specified in the message's headers.
The modern email library provides an EmailMessage object which replaces all the various individual MIME types which you had to use in the past to assemble a message from smaller parts. You can add attachments without separately constructing them, and build various more complex multipart structures if you need to, but you normally don't have to. Just create a message and populate the parts you want.
Notice that the following is heavily commented; on the whole, the new EmailMessage API is more succinct and more versatile than the old API.
from email.message import EmailMessage
msg = EmailMessage()
# This example uses explicit strings to emphasize that
# that's what these header eventually get turned into
msg["From"] = "me#example.org"
msg["To"] = "main.recipient#example.net, other.main.recipient#example.org"
msg["Cc"] = "secondary#example.com, tertiary#example.eu"
msg["Bcc"] = "invisible#example.int, undisclosed#example.org.au"
msg["Subject"] = "Hello from the other side"
msg.set_content("This is the main text/plain message.")
# You can put an HTML body instead by adding a subtype string argument "html"
# msg.set_content("<p>This is the main text/html message.</p>", "html")
# You can add attachments of various types as you see fit;
# if there are no other parts, the message will be a simple
# text/plain or text/html, but Python will change it into a
# suitable multipart/related or etc if you add more parts
with open("image.png", "rb") as picture:
msg.add_attachment(picture.read(), maintype="image", subtype="png")
# Which port to use etc depends on the mail server.
# Traditionally, port 25 is SMTP, but modern SMTP MSA submission uses 587.
# Some servers accept encrypted SMTP_SSL on port 465.
# Here, we use SMTP instead of SMTP_SSL, but pivot to encrypted
# traffic with STARTTLS after the initial handshake.
with smtplib.SMTP("smtp.example.org", 587) as server:
# Some servers insist on this, others are more lenient ...
# It is technically required by ESMTP, so let's do it
# (If you use server.login() Python will perform an EHLO first
# if you haven't done that already, but let's cover all bases)
server.ehlo()
# Whether or not to use STARTTLS depends on the mail server
server.starttls()
# Bewilderingly, some servers require a second EHLO after STARTTLS!
server.ehlo()
# Login is the norm rather than the exception these days
# but if you are connecting to a local mail server which is
# not on the public internet, this might not be useful or even possible
server.login("me.myself#example.org", "xyzzy")
# Finally, send the message
server.send_message(msg)
The ultimate visibility of the Bcc: header depends on the mail server. If you want to be really sure that the recipients are not visible to each other, perhaps don't put a Bcc: header at all, and separately enumerate the envelope recipients in the envelope like you used to have to with sendmail (send_message lets you do that too, but you don't have to if you just want to send to the recipients named in the headers).
This obviously sends a single message to all recipients in one go. That is generally what you should be doing if you are sending the same message to a lot of people. However, if each message is unique, you will need to loop over the recipients and create and send a new message for each. (Merely wishing to put the recipient's name and address in the To: header is probably not enough to warrant sending many more messages than required, but of course, sometimes you have unique content for each recipient in the body, too.)
you can try this when you write the recpient emails on a text file
from email.mime.text import MIMEText
from email.header import Header
import smtplib
f = open('emails.txt', 'r').readlines()
for n in f:
emails = n.rstrip()
server = smtplib.SMTP('smtp.uk.xensource.com')
server.ehlo()
server.starttls()
body = "Test Email"
subject = "Test"
from = "me#example.com"
to = emails
msg = MIMEText(body,'plain','utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = Header(from, 'utf-8')
msg['To'] = Header(to, 'utf-8')
text = msg.as_string()
try:
server.send(from, emails, text)
print('Message Sent Succesfully')
except:
print('There Was An Error While Sending The Message')
There are a lot of answers on here that are technically or partially correct. After reading everyone's answers, I came up with this as a more solid/universal email function. I have confirmed it works and you can pass HTML or plain text for the body. Note that this code does not include attachment code:
import smtplib
import socket
# Import the email modules we'll need
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
#
# #param [String] email_list
# #param [String] subject_line
# #param [String] error_message
def sendEmailAlert(email_list="default#email.com", subject_line="Default Subject", error_message="Default Error Message"):
hostname = socket.gethostname()
# Create message
msg = MIMEMultipart()
msg['Subject'] = subject_line
msg['From'] = f'no-reply#{hostname}'
msg['To'] = email_list
msg.attach(MIMEText(error_message, 'html'))
# Send the message via SMTP server
s = smtplib.SMTP('localhost') # Change for remote mail server!
# Verbose debugging
s.set_debuglevel(2)
try:
s.sendmail(msg['From'], msg['To'].split(","), msg.as_string())
except Exception as e:
print(f'EMAIL ISSUE: {e}')
s.quit()
This can obviously be modified to use native Python logging. I am just providing a solid core function. I also can't stress this enough, sendmail() wants a List and NOT a String! Function is for Python3.6+
Try declaring a list variable with all recipients and cc_recipients as strings than looping over them, like this:
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import smtplib
recipients = ["malcom#example.com","reynolds#example.com", "firefly#example.com"]
cc_recipients=["serenity#example.com", "inara#example.com"]
msg = MIMEMultipart()
msg["Subject"] = "Example"
msg["From"] = "me#example.com"
msg["To"] = ', '.join(recipients)
msg["Cc"] = ', '.join(cc_recipients)
body = MIMEText("example email body")
msg.attach(body)
smtp = smtplib.SMTP("mailhost.example.com", 25)
for recipient in recipients:
smtp.sendmail(msg["From"], recipient, msg.as_string())
for cc_recipient in cc_recipients:
smtp.sendmail(msg["From"], cc_recipient, msg.as_string())
smtp.quit()
For those who wish to send the message with only one 'To' header, the code below solves it. Ensure that your receivers variable is a list of strings.
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = title
msg['From'] = f'support#{config("domain_base")}'
msg['To'] = "me"
message_content += f"""
<br /><br />
Regards,<br />
Company Name<br />
The {config("domain_base")} team
"""
body = MIMEText(message_content, 'html')
msg.attach(body)
try:
smtpObj = smtplib.SMTP('localhost')
for r in receivers:
del msg['To']
msg['To'] = r #"Customer /n" + r
smtpObj.sendmail(f"support#{config('domain_base')}", r, msg.as_string())
smtpObj.quit()
return {"message": "Successfully sent email"}
except smtplib.SMTPException:
return {"message": "Error: unable to send email"}
To send email to multiple recipients add receivers as list of email id.
receivers = ['user1#email.com', 'user2#email.com', 'user3#email.com']
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
smtp_server = 'smtp-example.com'
port = 26
sender = 'user#email.com'
debuglevel = 0
# add receivers as list of email id string
receivers = ['user1#email.com', 'user2#email.com', 'user3#email.com']
message = MIMEMultipart(
"mixed", None, [MIMEImage(img_data, 'png'), MIMEText(html,'html')])
message['Subject'] = "Token Data"
message['From'] = sender
message['To'] = ", ".join(receivers)
try:
server = smtplib.SMTP('smtp-example.com')
server.set_debuglevel(1)
server.sendmail(sender, receivers, message.as_string())
server.quit()
# print(response)
except BaseException:
print('Error: unable to send email')
Here's my code
# Import smtplib to provide email functions
import smtplib
# Import the email modules
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Define email addresses to use
addr_to = 'user#outlook.com'
addr_from = 'user#aol.com'
# Define SMTP email server details
smtp_server = 'smtp.aol.com'
smtp_user = 'user#aol.com'
smtp_pass = 'pass'
# Construct email
msg = MIMEMultipart('alternative')
msg['To'] = addr_to
msg['From'] = addr_from
msg['Subject'] = 'test test test!'
# Create the body of the message (a plain-text and an HTML version).
text = "This is a test message.\nText and html."
html = """\
"""
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via an SMTP server
s = smtplib.SMTP(smtp_server)
s.login(smtp_user,smtp_pass)
s.sendmail(addr_from, addr_to, msg.as_string())
s.quit()
I just want the email received to display the sender name before sender email address like this : sender_name
In the year 2020 and Python 3, you do things like this:
from email.utils import formataddr
from email.message import EmailMessage
import smtplib
msg = EmailMessage()
msg['From'] = formataddr(('Example Sender Name', 'john#example.com'))
msg['To'] = formataddr(('Example Recipient Name', 'jack#example.org'))
msg.set_content('Lorem Ipsum')
with smtplib.SMTP('localhost') as s:
s.send_message(msg)
It depends on whether the "friendly name" is basic ASCII or requires special characters.
Basic example:
msg['From'] = str(Header('Magnus Eisengrim <meisen99#gmail.com>'))
If you need to use non US-ASCII characters, it's more complex, but the attached article should help, it is very thorough: http://blog.magiksys.net/generate-and-send-mail-with-python-tutorial
This is an old question - however, I faced the same problem and came up with the following:
msg['From'] = formataddr((str(Header('Someone Somewhere', 'utf-8')), 'xxxxx#gmail.com'))
You'll need to import from email.header import Header and from email.utils import formataddr.
That would make only the sender name appear on the inbox, without the <xxxxx#gmail.com>:
While the email body would include the full pattern:
Putting the sender name and the email in one string (Sender Name <sender#server.com>) would make some email clients show the it accordingly on the receiver's inbox (unlike the first picture, showing only the name).
I took the built-in example and made it with this:
mail_body = "the email body"
mailing_list = ["user1#company.com"]
msg = MIMEText(mail_body)
me = 'John Cena <mail#company.com>'
you = mailing_list
msg['Subject'] = subject
msg['From'] = me
msg['To'] = mailing_list
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()
I found that if I send an email with gmail and set the From header to sender name <email#gmail.com>, the email arrives with the From like:
From sender name email#gmail.com email#gmail.com.
So I guess at least with gmail you should set the From header like as follow:
msg['From'] = "sender name"
You can use below mentioned code, you just need to change sender and receiver with user name and password, it will work for you.
import smtplib
sender = 'xyz#gmail.com'
receivers = ['abc#gmail.com']
message = """From: sender_name <xyz#gmail.com>
To: reciever_name <abc#gmail.com>
Subject: sample test mail
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('smtp_server',port)
smtpObj.sendmail(sender, receivers, message)
smtpObj.login(user,password)
print ("Successfully sent email")
except:
print ("Error: unable to send email")
for more detail please visit https://www.datadivein.com/2018/03/how-to-auto-send-mail-using-python.html
I've tried sending mail with python from gmail and it works fine. But the problem is when I created the Mail class with one method to whom I send specific string from my code, it can't be send.
class Mail:
def send_mail(self, msg):
import smtplib
fromaddr = 'something#something.com'
toaddrs = 'something#gmail.com'
msg = msg + "something"
print msg
username = 'something'
password = 'something'
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
This way it sends mail but the only thing in mail is "something" that I added to string, and print msg outputs the whole string plus "something". What could be the problem?
This is the whole class for now, and it's called
mail = Mail()
mail.send_mail(message)
I don't know what was the problem, but I managed to send it using MIME that's already in python
So here is the code that works:
def send_mail(self, message):
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
gmailUser = 'something#gmail.com'
gmailPassword = 'something'
recipient = 'something#something.com'
msg = MIMEMultipart()
msg['From'] = gmailUser
msg['To'] = recipient
msg['Subject'] = "Subject"
msg.attach(MIMEText(message))
mailServer = smtplib.SMTP('smtp.gmail.com', 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmailUser, gmailPassword)
mailServer.sendmail(gmailUser, recipient, msg.as_string())
mailServer.close()
The problem is most likely that the content of the message seems to requite an extra line break between the addresses and the body of the message. The solution given by iblazevic is a much more readable way of doing it anyway though.
After much searching I couldn't find out how to use smtplib.sendmail to send to multiple recipients. The problem was every time the mail would be sent the mail headers would appear to contain multiple addresses, but in fact only the first recipient would receive the email.
The problem seems to be that the email.Message module expects something different than the smtplib.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.
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import smtplib
msg = MIMEMultipart()
msg["Subject"] = "Example"
msg["From"] = "me#example.com"
msg["To"] = "malcom#example.com,reynolds#example.com,firefly#example.com"
msg["Cc"] = "serenity#example.com,inara#example.com"
body = MIMEText("example email body")
msg.attach(body)
smtp = smtplib.SMTP("mailhost.example.com", 25)
smtp.sendmail(msg["From"], msg["To"].split(",") + msg["Cc"].split(","), msg.as_string())
smtp.quit()
This really works, I spent a lot of time trying multiple variants.
import smtplib
from email.mime.text import MIMEText
s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = 'me#example.com'
recipients = ['john.doe#example.com', 'john.smith#example.co.uk']
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())
The msg['To'] needs to be a string:
msg['To'] = "a#b.com, b#b.com, c#b.com"
While the recipients in sendmail(sender, recipients, message) needs to be a list:
sendmail("a#a.com", ["a#b.com", "b#b.com", "c#b.com"], "Howdy")
You need to understand the difference between the visible address of an email, and the delivery.
msg["To"] is essentially what is printed on the letter. It doesn't actually have any effect. Except that your email client, just like the regular post officer, will assume that this is who you want to send the email to.
The actual delivery however can work quite different. So you can drop the email (or a copy) into the post box of someone completely different.
There are various reasons for this. For example forwarding. The To: header field doesn't change on forwarding, however the email is dropped into a different mailbox.
The smtp.sendmail command now takes care of the actual delivery. email.Message is the contents of the letter only, not the delivery.
In low-level SMTP, you need to give the receipients one-by-one, which is why a list of adresses (not including names!) is the sensible API.
For the header, it can also contain for example the name, e.g. To: First Last <email#addr.tld>, Other User <other#mail.tld>. Your code example therefore is not recommended, as it will fail delivering this mail, since just by splitting it on , you still not not have the valid adresses!
It works for me.
import smtplib
from email.mime.text import MIMEText
s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = 'me#example.com'
recipients = 'john.doe#example.com,john.smith#example.co.uk'
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = recipients
s.sendmail(sender, recipients.split(','), msg.as_string())
The solution below worked for me. It successfully sends an email to multiple recipients, including "CC" and "BCC."
toaddr = ['mailid_1','mailid_2']
cc = ['mailid_3','mailid_4']
bcc = ['mailid_5','mailid_6']
subject = 'Email from Python Code'
fromaddr = 'sender_mailid'
message = "\n !! Hello... !!"
msg['From'] = fromaddr
msg['To'] = ', '.join(toaddr)
msg['Cc'] = ', '.join(cc)
msg['Bcc'] = ', '.join(bcc)
msg['Subject'] = subject
s.sendmail(fromaddr, (toaddr+cc+bcc) , message)
So actually the problem is that SMTP.sendmail and email.MIMEText need two different things.
email.MIMEText sets up the "To:" header for the body of the e-mail. It is ONLY used for displaying a result to the human being at the other end, and like all e-mail headers, must be a single string. (Note that it does not actually have to have anything to do with the people who actually receive the message.)
SMTP.sendmail, on the other hand, sets up the "envelope" of the message for the SMTP protocol. It needs a Python list of strings, each of which has a single address.
So, what you need to do is COMBINE the two replies you received. Set msg['To'] to a single string, but pass the raw list to sendmail:
emails = ['a.com','b.com', 'c.com']
msg['To'] = ', '.join( emails )
....
s.sendmail( msg['From'], emails, msg.as_string())
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def sender(recipients):
body = 'Your email content here'
msg = MIMEMultipart()
msg['Subject'] = 'Email Subject'
msg['From'] = 'your.email#gmail.com'
msg['To'] = (', ').join(recipients.split(','))
msg.attach(MIMEText(body,'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('your.email#gmail.com', 'yourpassword')
server.send_message(msg)
server.quit()
if __name__ == '__main__':
sender('email_1#domain.com,email_2#domain.com')
It only worked for me with send_message function and using the join function in the list whith recipients, python 3.6.
I tried the below and it worked like a charm :)
rec_list = ['first#example.com', 'second#example.com']
rec = ', '.join(rec_list)
msg['To'] = rec
send_out = smtplib.SMTP('localhost')
send_out.sendmail(me, rec_list, msg.as_string())
I came up with this importable module function. It uses the gmail email server in this example. Its split into header and message so you can clearly see whats going on:
import smtplib
def send_alert(subject=""):
to = ['email#one.com', 'email2#another_email.com', 'a3rd#email.com']
gmail_user = 'me#gmail.com'
gmail_pwd = 'my_pass'
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + ", ".join(to) + '\n' + 'From: ' + gmail_user + '\n' + 'Subject: ' + subject + '\n'
msg = header + '\n' + subject + '\n\n'
smtpserver.sendmail(gmail_user, to, msg)
smtpserver.close()
I use python 3.6 and the following code works for me
email_send = 'xxxxx#xxx.xxx,xxxx#xxx.xxx'
server.sendmail(email_user,email_send.split(','),text)
I figured this out a few months back and blogged about it. The summary is:
If you want to use smtplib to send email to multiple recipients, use email.Message.add_header('To', eachRecipientAsString) to add them, and then when you invoke the sendmail method, use email.Message.get_all('To') send the message to all of them. Ditto for Cc and Bcc recipients.
Well, the method in this asnwer method did not work for me. I don't know, maybe this is a Python3 (I am using the 3.4 version) or gmail related issue, but after some tries, the solution that worked for me, was the line
s.send_message(msg)
instead of
s.sendmail(sender, recipients, msg.as_string())
This is an old question. My main reason to post a new answer is to explain how to solve the problem with the modern email library in Python 3.6+ and how it differs from the old version; but first, let's recap what Anony-Mousse wrote in their answer from 2012.
SMTP doesn't care at all what's in the headers. The list of recipients you pass in to the sendmail method are what actually determine where the message will be delivered.
In SMTP parlance, this is called the message's envelope. On the protocol level, you connect to the server, then tell it who the message is from (MAIL FROM: SMTP verb) and who to send it to (RCPT TO:), then separately transmit the message itself (DATA) with headers and body as one oblique string blob.
The modern smtplib simplifies the Python side of this by providing a send_message method which actually sends to the recipients specified in the message's headers.
The modern email library provides an EmailMessage object which replaces all the various individual MIME types which you had to use in the past to assemble a message from smaller parts. You can add attachments without separately constructing them, and build various more complex multipart structures if you need to, but you normally don't have to. Just create a message and populate the parts you want.
Notice that the following is heavily commented; on the whole, the new EmailMessage API is more succinct and more versatile than the old API.
from email.message import EmailMessage
msg = EmailMessage()
# This example uses explicit strings to emphasize that
# that's what these header eventually get turned into
msg["From"] = "me#example.org"
msg["To"] = "main.recipient#example.net, other.main.recipient#example.org"
msg["Cc"] = "secondary#example.com, tertiary#example.eu"
msg["Bcc"] = "invisible#example.int, undisclosed#example.org.au"
msg["Subject"] = "Hello from the other side"
msg.set_content("This is the main text/plain message.")
# You can put an HTML body instead by adding a subtype string argument "html"
# msg.set_content("<p>This is the main text/html message.</p>", "html")
# You can add attachments of various types as you see fit;
# if there are no other parts, the message will be a simple
# text/plain or text/html, but Python will change it into a
# suitable multipart/related or etc if you add more parts
with open("image.png", "rb") as picture:
msg.add_attachment(picture.read(), maintype="image", subtype="png")
# Which port to use etc depends on the mail server.
# Traditionally, port 25 is SMTP, but modern SMTP MSA submission uses 587.
# Some servers accept encrypted SMTP_SSL on port 465.
# Here, we use SMTP instead of SMTP_SSL, but pivot to encrypted
# traffic with STARTTLS after the initial handshake.
with smtplib.SMTP("smtp.example.org", 587) as server:
# Some servers insist on this, others are more lenient ...
# It is technically required by ESMTP, so let's do it
# (If you use server.login() Python will perform an EHLO first
# if you haven't done that already, but let's cover all bases)
server.ehlo()
# Whether or not to use STARTTLS depends on the mail server
server.starttls()
# Bewilderingly, some servers require a second EHLO after STARTTLS!
server.ehlo()
# Login is the norm rather than the exception these days
# but if you are connecting to a local mail server which is
# not on the public internet, this might not be useful or even possible
server.login("me.myself#example.org", "xyzzy")
# Finally, send the message
server.send_message(msg)
The ultimate visibility of the Bcc: header depends on the mail server. If you want to be really sure that the recipients are not visible to each other, perhaps don't put a Bcc: header at all, and separately enumerate the envelope recipients in the envelope like you used to have to with sendmail (send_message lets you do that too, but you don't have to if you just want to send to the recipients named in the headers).
This obviously sends a single message to all recipients in one go. That is generally what you should be doing if you are sending the same message to a lot of people. However, if each message is unique, you will need to loop over the recipients and create and send a new message for each. (Merely wishing to put the recipient's name and address in the To: header is probably not enough to warrant sending many more messages than required, but of course, sometimes you have unique content for each recipient in the body, too.)
you can try this when you write the recpient emails on a text file
from email.mime.text import MIMEText
from email.header import Header
import smtplib
f = open('emails.txt', 'r').readlines()
for n in f:
emails = n.rstrip()
server = smtplib.SMTP('smtp.uk.xensource.com')
server.ehlo()
server.starttls()
body = "Test Email"
subject = "Test"
from = "me#example.com"
to = emails
msg = MIMEText(body,'plain','utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = Header(from, 'utf-8')
msg['To'] = Header(to, 'utf-8')
text = msg.as_string()
try:
server.send(from, emails, text)
print('Message Sent Succesfully')
except:
print('There Was An Error While Sending The Message')
There are a lot of answers on here that are technically or partially correct. After reading everyone's answers, I came up with this as a more solid/universal email function. I have confirmed it works and you can pass HTML or plain text for the body. Note that this code does not include attachment code:
import smtplib
import socket
# Import the email modules we'll need
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
#
# #param [String] email_list
# #param [String] subject_line
# #param [String] error_message
def sendEmailAlert(email_list="default#email.com", subject_line="Default Subject", error_message="Default Error Message"):
hostname = socket.gethostname()
# Create message
msg = MIMEMultipart()
msg['Subject'] = subject_line
msg['From'] = f'no-reply#{hostname}'
msg['To'] = email_list
msg.attach(MIMEText(error_message, 'html'))
# Send the message via SMTP server
s = smtplib.SMTP('localhost') # Change for remote mail server!
# Verbose debugging
s.set_debuglevel(2)
try:
s.sendmail(msg['From'], msg['To'].split(","), msg.as_string())
except Exception as e:
print(f'EMAIL ISSUE: {e}')
s.quit()
This can obviously be modified to use native Python logging. I am just providing a solid core function. I also can't stress this enough, sendmail() wants a List and NOT a String! Function is for Python3.6+
Try declaring a list variable with all recipients and cc_recipients as strings than looping over them, like this:
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import smtplib
recipients = ["malcom#example.com","reynolds#example.com", "firefly#example.com"]
cc_recipients=["serenity#example.com", "inara#example.com"]
msg = MIMEMultipart()
msg["Subject"] = "Example"
msg["From"] = "me#example.com"
msg["To"] = ', '.join(recipients)
msg["Cc"] = ', '.join(cc_recipients)
body = MIMEText("example email body")
msg.attach(body)
smtp = smtplib.SMTP("mailhost.example.com", 25)
for recipient in recipients:
smtp.sendmail(msg["From"], recipient, msg.as_string())
for cc_recipient in cc_recipients:
smtp.sendmail(msg["From"], cc_recipient, msg.as_string())
smtp.quit()
For those who wish to send the message with only one 'To' header, the code below solves it. Ensure that your receivers variable is a list of strings.
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = title
msg['From'] = f'support#{config("domain_base")}'
msg['To'] = "me"
message_content += f"""
<br /><br />
Regards,<br />
Company Name<br />
The {config("domain_base")} team
"""
body = MIMEText(message_content, 'html')
msg.attach(body)
try:
smtpObj = smtplib.SMTP('localhost')
for r in receivers:
del msg['To']
msg['To'] = r #"Customer /n" + r
smtpObj.sendmail(f"support#{config('domain_base')}", r, msg.as_string())
smtpObj.quit()
return {"message": "Successfully sent email"}
except smtplib.SMTPException:
return {"message": "Error: unable to send email"}
To send email to multiple recipients add receivers as list of email id.
receivers = ['user1#email.com', 'user2#email.com', 'user3#email.com']
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
smtp_server = 'smtp-example.com'
port = 26
sender = 'user#email.com'
debuglevel = 0
# add receivers as list of email id string
receivers = ['user1#email.com', 'user2#email.com', 'user3#email.com']
message = MIMEMultipart(
"mixed", None, [MIMEImage(img_data, 'png'), MIMEText(html,'html')])
message['Subject'] = "Token Data"
message['From'] = sender
message['To'] = ", ".join(receivers)
try:
server = smtplib.SMTP('smtp-example.com')
server.set_debuglevel(1)
server.sendmail(sender, receivers, message.as_string())
server.quit()
# print(response)
except BaseException:
print('Error: unable to send email')