0

Based on answer to question "How do I reply to an email using the Python imaplib and include the original message?" I did try to create function to answer with multi "Cc" sending.

def send_answer(original, file_to_attach, body_text="Macros reply", cc_addrs: list = []):
# https://stackoverflow.com/questions/2182196/how-do-i-reply-to-an-email-using-the-python-imaplib-and-include-the-original-mes

import smtplib
import ssl

# Then create a reply message:
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase

new = MIMEMultipart("mixed")
body = MIMEMultipart("alternative")
body.attach(MIMEText(body_text, "plain"))
body.attach(MIMEText(f"<html> {body_text} </html>", "html"))
new.attach(body)

new["Message-ID"] = email.utils.make_msgid()
new["In-Reply-To"] = original["Message-ID"]
new["References"] = original["Message-ID"]
new["Subject"] = "Re: " + original["Subject"]
new["To"] = original["From"].lower()
new["From"] = user

if cc_addrs:
    new['Cc'] = ",".join(cc_addrs)

#  Then attach the file:  file_to_attach
file_name = file_to_attach.name
part = MIMEBase('application', 'octet-stream')
with open(file_to_attach, 'rb') as attachment:
    part.set_payload(attachment.read())
email.encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename=file_name)
new.attach(part)

context = ssl.create_default_context()
with smtplib.SMTP('smtp.gmail.com', 587) as s:   # creates SMTP session
    s.ehlo()                            # Can be omitted
    s.starttls(context=context)         # start TLS for security
    s.ehlo()                            # Can be omitted
    s.login(user, password)  # Authentication  # "Password_of_the_sender"
    s.set_debuglevel(True)
    s.send_message(new)

It works in strange manner:

  1. answer with attachment was received by sender (it's Ok)
  2. no-one from "Cc" list receive the answer
  3. gmail shows that copies was sent gmail says

here is the headers:

send: 'mail FROM:<vasilij.kolomiets@gmail.com> size=505259\r\n'

enter image description here

and end the debug message:

enter image description here

So, the question is - HOW to send copy to many receivers in list?

Vasyl Kolomiets
  • 365
  • 8
  • 20
  • 1
    This is an old answer, but see if it helps: [Mail not being sent to people in CC](https://stackoverflow.com/questions/9974972/mails-not-being-sent-to-people-in-cc) – evergreen Mar 24 '21 at 19:01
  • https://docs.python.org/3/library/smtplib.html?highlight=send_message#smtplib.SMTP.send_message I believe in If from_addr is None or to_addrs is None, send_message fills those arguments with addresses extracted from the headers of msg as specified in RFC 5322: from_addr is set to the Sender field if it is present, and otherwise to the From field. to_addrs combines the values (if any) of the To, Cc, and Bcc fields from msg. – Vasyl Kolomiets Mar 24 '21 at 22:45

0 Answers0