Home > Net >  Python- Send email using css
Python- Send email using css

Time:11-03

I am trying to send an email using this function I have written:

def send_email(recip, subj, content):
    email = MIMEMultipart('alternative')
    email['To'] = ",".join(recip)
    email['From'] = '[email protected]'
    email['Subject'] = subj
    body = MIMEText(content, 'html')
    email.attach(body)
    smtpObj = smtplib.SMTP('something.com')
    smtpObj.sendmail('[email protected]', recip, email.as_string())

The email is sent and when I view the source I can also my css code there but it is clearly not using the CSS code. I am using Outlook.

             <html>
                <head> <style>
                    {css}
                </style> </head>
                <body>
                <img src = "header.png">
                    <div>
                        <h6> Trade Date - {date} </h6>
                    </div>
                    <div>
                        <h6> SUMMARY </h6>
                        {summary}
                    </div>
                    <div>
                        <h6> DETAILS </h6>
                        {details}
                    </div>
                    <div>
                        <h6> INTERNAL DESKS </h6>
                        {desk}
                    </div>
                </body>
                </html>

The above is my html code structured and the css code appears in the {css} area. Can anyone tell me what vis going wrong? I know Outlook should support style tags inside head like I am doing

CodePudding user response:

Each email client (Outlook, Thunderbird, Gmail in a web browser, etc.) handles CSS differently. But the end result is that you generally should NOT rely on CSS embedded in head elements - it just doesn't work reliably in email. What mostly works is to use inline CSS - i.e., CSS on the actual HTML elements in the body. See this article for a reasonable explanation.

This is an old problem, with no real solution in sight. There are paid services which can test an email message in a bunch of different clients, or you can manually test (e.g., in addition to Outlook which you already have, install Thunderbird (free) and setup a gmail account (free) and you can cover a large percentage of email users with relatively little effort).

CodePudding user response:

For best interoperability, you should write inline CSS only. That is, using style="..." attributes to your elements.

Some email clients will simply ignore your <style> elements.

  • Related