SMTP - несколько получателей при отправке с Gmail, даже скрытая копия не доходит
Не получается отправить на нескольких получателей письмо с Gmail. Читая это и это, попробовал оба варианта - добавить скрытую копию при помощи msg['Bcc'] = bcc_addrs и список адресов получателей в поле msg['To'] = to_addr.
Письмо на одного адресата (без bcc_addrs) нормально доходит. Вот код:
from pathlib import Path
def send_mail_with_attach(
to_addr, mail_subject, bcc_addrs=None,
mail_body="by Python script",
files_to_attach=[Path(r"D:\OneDrive\PyCodes\SСHEDULER\tenor_Mister_Bin.gif"), ]
):
# Python code to Send mail with attachments
# from your Gmail account
# https://stackoverflow.com/questions/26582811/gmail-python-multiple-attachments
# https://realpython.com/python-send-email/
# https://code.tutsplus.com/ru/tutorials/sending-emails-in-python-with-smtp--cms-29975
# error codes:
# https://docs.microsoft.com/ru-ru/exchange/mail-flow/test-smtp-with-telnet?view=exchserver-2019
# libraries to be imported
import smtplib
import ssl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from email.utils import formatdate
# instance of MIMEMultipart
msg = MIMEMultipart()
# storing the senders email address
msg['From'] = user
# storing the receivers email address
msg['To'] = to_addr
# storing the subject
msg['Subject'] = mail_subject # "Subject of the Mail"
msg["Date"] = formatdate(localtime=True)
if bcc_addrs:
msg['Bcc'] = bcc_addrs
# attach the body with the msg instance
msg.attach(MIMEText(mail_body, 'plain')) # "Body_of_the_mail"
try:
for file in files_to_attach:
part = MIMEBase('application', 'octet-stream')
with open(file, "rb") as fh: # open the file to be sent
data = fh.read()
filename = file.name
part.set_payload(data)
encoders.encode_base64(part)
part.add_header('Content-Disposition', f'attachment; filename="{filename}"')
msg.attach(part)
except IOError:
msg = f"Error opening attachment file {file.name}"
print(msg)
sys.exit(1)
# Converts the Multipart msg into a string
text = msg.as_string()
context = ssl.create_default_context()
with smtplib.SMTP('smtp.gmail.com', 587) as s: # creates SMTP session
s.ehlo() # Can be omitted
# start TLS for security
s.starttls(context=context)
s.ehlo() # Can be omitted
# Authentication
s.login(user, password) # "Password_of_the_sender"
s.set_debuglevel(True)
# sending the mail
s.sendmail(user, to_addr, text)
Вызываю с bcc_addrs - в почте Gmail показывает что есть адресат скрытой копии, но он ничего не получает. Основной адресат письмо получает. Сообщения об ошибке вроде нет. Вот начало и хвостик:
send: 'mail FROM:<[email protected]> size=223180\r\n'
reply: b'250 2.1.0 OK t4sm503059lff.260 - gsmtp\r\n'
reply: retcode (250); Msg: b'2.1.0 OK t4sm503059lff.260 - gsmtp'
send: 'rcpt TO:<[email protected]>\r\n'
reply: b'250 2.1.5 OK t4sm503059lff.260 - gsmtp\r\n'
reply: retcode (250); Msg: b'2.1.5 OK t4sm503059lff.260 - gsmtp'
send: 'data\r\n'
reply: b'354 Go ahead t4sm503059lff.260 - gsmtp\r\n'
reply: retcode (354); Msg: b'Go ahead t4sm503059lff.260 - gsmtp'
data: (354, b'Go ahead t4sm503059lff.260 - gsmtp')
send: b'Content-Type: multipart/mixed; boundary="===============7632431358522942351=="\r\nMIME-Version: 1.0\r\nFrom: [email protected]\r\nTo: [email protected]\r\nSubject: =?utf-8?b?0L/QuNGB0YzQvNC+IDIgIDEyOjUzICBiY2NfYWRkcnM9J3Zhc2lsaWoua29sb21pZXRzQGdtYWlsLmNvbScgLyBkYXRlIC8gIFVrcg==?=\r\nDate: Thu, 21 Jan 2021 12:53:12 +0200\r\nBcc: [email protected]\r\n\r\nUkraine\r\n--===============7632431358522942351==\r\nContent-Type: text/plain; charset="us-ascii"\r\nMIME-Version: 1.0\r\nContent-Transfer-Encoding: 7bit\r\n\r\nby Python script\r\n--===============7632431358522942351==\r\nContent-Type: application/octet-stream\r\nMIME-Version: 1.0\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename="tenor_Mister_Bin.gif"\r\n\
...
===============7632431358522942351==--\r\n.\r\n'
reply: b'250 2.0.0 OK 1611226415 t4sm503059lff.260 - gsmtp\r\n'
reply: retcode (250); Msg: b'2.0.0 OK 1611226415 t4sm503059lff.260 - gsmtp'
data: (250, b'2.0.0 OK 1611226415 t4sm503059lff.260 - gsmtp')
send: 'QUIT\r\n'
reply: b'221 2.0.0 closing connection t4sm503059lff.260 - gsmtp\r\n'
reply: retcode (221); Msg: b'2.0.0 closing connection t4sm503059lff.260 - gsmtp'
Итого вопрос - как же отправить письмо сразу нескольким адресатам.
При указании списка адресов типа: to_addr = "[email protected], [email protected]", письмо числится в отправленных, все адреса разобраны, но ни один получатель ничего не получает.
Ответы (1 шт):
...
sender = '[email protected]'
recipients = ['[email protected]', '[email protected]']
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())
Используйте список для получателей.