Python Smtplib BCC issue?

3.8k views Asked by At

I wonder anyone can assist on this.

I have this python code which can send email.

import smtplib
import string
import sys
import os

fromaddr = '[email protected]'

toaddr = '[email protected]'
cc = []
bcc = ['[email protected]', '[email protected]']
subject = 'This is a test email'

msg = string.join((
    'From: %s' % fromaddr,
    'To: %s' % toaddr,
    'CC: %s' % ', '.join(cc),
    'BCC: %s' % ', '.join(bcc),
    'Subject: %s' % subject, '',
    'hello world'
), '\r\n')

print msg

toaddrs = [toaddr] + cc + bcc

print toaddrs

server = smtplib.SMTP('smtp.googlemail.com',587)
server.starttls()
server.login('my_gmail_account','my_gmail_password')
server.sendmail(fromaddr,toaddrs,msg)
server.quit()

The problem I have is for those who I bcc'ed i.e. [email protected] and [email protected], they could see who's inside the bcc'd list.

Example,

From : [email protected]
To : [email protected]
Bcc : [email protected],[email protected]

This is not the right format.

I am expecting the results should be like this.

a. For [email protected] user

this person should see this

From : [email protected]
To : [email protected]
Bcc : this is hidden

b. For [email protected] user

this person should see this

From : [email protected]
To : [email protected]
Bcc : [email protected]

c. For [email protected] user

this person should see this

From : [email protected]
To : [email protected]
Bcc : [email protected]

Any way to enhance my python smtplib codes to achieve the above?

Thanks in advance.

2

There are 2 answers

0
zoof On

the sendmail method from python's smtplib module does not honor rfc 822 regarding the bcc header. Instead, it just parses a bunch of text and sends all of it, including bcc, to everyone in to, cc, and bcc. If you can upgrade to python3, python3's smtplib includes a method, send_message, which will handle bcc headers correctly.

0
ToBeFrank On

Remove the BCC header, but keep the bcc recipients in toaddrs. The bcc recipients will all receive the email, but the email clients won't display them as recipients.