create Email with multiple HTML blocks embedded

Thomas 'PointedEars' Lahn PointedEars at web.de
Tue Jan 5 18:58:59 EST 2016


kevind0718 at gmail.com wrote:
^^^^^^^^^^^^^^^^^^^^
Please either do not use Google Groups and configure your newsreader 
accordingly (recommended), or use Google Groups to subscribe to the 
newsgroup so that you can specify your real name.

> body = MIMEMultipart('multipart')

Obviously there is redundancy, so common sense should tell you already that 
this cannot be correct.  The manual says:

<https://docs.python.org/3/library/email.mime.html#email.mime.multipart.MIMEMultipart>

| class email.mime.multipart.MIMEMultipart(_subtype='mixed', boundary=None, 
| _subparts=None, **_params)
| 
| Module: email.mime.multipart
| 
| A subclass of MIMEBase, this is an intermediate base class for MIME 
| messages that are multipart. Optional _subtype defaults to mixed, but can 
| be used to specify the subtype of the message. A Content-Type header of 
| multipart/_subtype will be added to the message object.

So this would add a “Content-Type” header (field) with the value 
“multipart/multipart” to the constructed *message object*, referred to by 
*body* (see below).  It has to be “multipart/mixed” in your case instead, 
which is the default.  So you need to write *only*

msg = MIMEMultipart()

which you did.  But:
 
> with open("H:\\dev\\testHTML\\Exceptions_SheetDec30d.htm", "r") as fE:
>     htmlE = fE.read().replace('\n', '')
> 
> 
> with open("H:\\dev\\testHTML\\Summary_SheetDec30d.htm", "r") as f:
>     html = f.read().replace('\n', '')
> 
> body.attach(MIMEText(html, 'html'))
> body.attach(MIMEText(htmlE, 'html'))
> 
> msg.attach(body)

Here you are attaching to a multi-part message a *multi-part message with 
two parts*:

  msg (multipart/mixed)
  '- body (multipart/multipart)
     :- html  (text/html)
     '- htmlE (text/html)

You want instead:

  msg (multipart/mixed)
  :- html  (text/html)
  '- htmlE (text/html)

In code:

  msg.attach(MIMEText(html, 'html'))
  msg.attach(MIMEText(htmlE, 'html'))

So just skip ”body”.  (Where else but to the body of the message would you 
attach parts?  To the header? ;-))

You can see how it works *before* you sent the e-mail if you call

  print(msg)

(Of course, you can also read the e-mail source after it was delivered.)

It is unnecessary/wrong to remove the '\n's from the HTML before transfer 
encoding by MIMEText().

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.



More information about the Python-list mailing list