I have been testing my code to send email to multiple recipients, but i came across a strange observation:
message["To"] = 'email_one.sample.com, email_two.sample.com'
sendmail(mine_email, ['email_one.sample.com'], message.as_string())
The above two lines give me an output wherein i get to see the email_id of both recipients in the header's section but despite the fact that i only passed a single recipient's id in the sendmail() method, the email is sent to both id's nonetheless.
Also vice versa if i pass a single email_id into the message["To"] and multiple email_id's in the sendmail() method the email is sent to all of the recipients in the sendmail() method but they only see a single id in the header section.
So now i am a bit confused as to what exactly happens behind the scenes that causes such strange behaviour. How exactly does a recipient whose email_id i do not pass into the sendmail() method receive an email, just by passing that email id into the message["To"] part.
P.S.: i have already seen the below answer and although it covers the syntax in great details i am merely asking about the strange behaviour pertaining to my above mentioned problem
The observation is due to how the SMTP works, so in the email there are generally 2 types of "To" addresses - one which is the actual email address to which email is sent to(envelope to
) and another being the one which users can see in the email body(header to
).
For example, say you sent an email to two recipients one as a BCC recipient and other as a CC recipient from some email client, then the envelope to
will have the addresses of both sender but the to header
will not have the BCC recipient's address. So the SMTP server(MTA Mail Transfer Agent) will see that the email is meant for both the recipients, but when email is received by the recipients they will see that it was only sent to one recipient.
Here's a sample SMTP transaction -
=== Connected to mysmtpserver.com
-> EHLO MYHOST
<- 250-mysmtpserver.com says EHLO to 10.128.22.119:53831
<- 250-8BITMIME
<- 250-ENHANCEDSTATUSCODES
<- 250-STARTTLS
<- 250-PIPELINING
-> MAIL FROM:<me@somone.com>
<- 250 2.0.0 MAIL FROM accepted
-> RCPT TO:<my_friend@his.domain.com>
<- 250 2.0.0 RCPT TO accepted
-> DATA
<- 354 3.0.0 continue. finished with "\r\n.\r\n"
-> Date: Fri, 03.1 Aug 2018 00:24:53 +0530
-> To: my_friend@his.domain.com
-> From: me@somone.com
-> Subject: Just having fun testing
-> Message-Id: <20180803002453.066266@MYHOST>
-> SOME-OTHER-HEADER: my friend! He can't see this in his email client
->
-> This is body, my friend can see this
->
-> .
<- 250 2.0.0 2983ksndafkn092 mail accepted for delivery
-> QUIT
<- 221 2.3.0 mysmtpserver.com closing connection
Note that if the toaddr
argument to the sendmail
function is None
, then it will pick up all the recipient addresses from the message headers(BCC
, CC
and To
) and then use them as envelope recipients
.
Here's the cpython source code.