jim jarnac
jim jarnac

Reputation: 5152

python MIME attaching multiple attachments to a multipart message

I am trying to attach multiple attachments to a email.mime.multipart object:

from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

message = MIMEMultipart('alternative')
message['Subject'] = 'test'

for i in range(10):
    title="<h2>{}</h2>".format(i)
    message.attach(MIMEText(title,"html",_charset="utf-8"))

Here I can check that the payload contains the 10 elements:
message.get_payload()
I can see the list of 10 elements, which seems correct.

However when I send the email with the following code:

MAIL_HOST = 'smtp.gmail.com:587'
MAIL_USER = '[email protected]'
MAIL_PASSWORD = 'xxx'
MAIL_REPICIENTS = ['[email protected]']

smtp = SMTP(MAIL_HOST)
smtp.ehlo()
smtp.starttls()
smtp.login(MAIL_USER, MAIL_PASSWORD)
smtp.sendmail(MAIL_USER, MAIL_REPICIENTS, message.as_string())
smtp.close()

The email contains only the last element of the list.

Can anyone help me with that?

Upvotes: 1

Views: 1446

Answers (1)

Steampunkery
Steampunkery

Reputation: 3874

That’s because you are attaching 10 different messages. Why you want is to attach one message. Change your code to this:

from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

message = MIMEMultipart('alternative')
message['Subject'] = 'test'
html = ''

for i in range(10):
    title="<h2>{}</h2>".format(i)
    html += title

message.attach(MIMEText(html,"html",_charset="utf-8"))

Upvotes: 2

Related Questions