How to Code HTML Emails for Any Device
How to Code HTML Emails for Any Device
In the broader web design world, we’ve been through the browser wars where Netscape and Internet Explorer fought each other to introduce competing ways to code just about everything. Thanks to the Web Standards Project and associated efforts, modern web browsers are much more consistent than they were ten years ago.
Even worse than not trying to improve their HTML and CSS rendering, some email clients have actually gone backwards. Thirteen years ago, Microsoft decided Outlook 2007 would stop using Internet Explorer to render HTML emails. Before you get all excited, they were replacing it with Microsoft Word. Yes—Microsoft Word: the word processor. In one version, Outlook went from being decent and understandable, to downright terrible at displaying HTML emails from anyone except other Outlook users.
Outlook still uses the Microsoft Word rendering engine in all it’s Windows Desktop apps, with each iteration being given a version number (except the latest: Outlook 2016 and 2019 are the same, much to our dismay).
And Outlook is still a hugely popular email client, but that introduces even more problems: Building HTML for email means you’re dealing with more than four or five major web browsers, and 12 to 15 different email clients, each with solid market share. Litmus once posited that if you count every iteration of email client/browser/product model, it would be 15,000 different possibilities!
Some of them are great, like Apple Mail. A design that works in Safari will be perfect in Apple Mail. Some, like Outlook, cause stress and anxiety for every email developer. Gmail currently has the highest market share (see the rest of the breakdown on the Email Market Share site by Litmus), and Gmail has its own intricacies. In between are a whole slew of different rendering constraints, quirks, and inconsistencies.
Fonts
The simplest and the most reliable decision is to use safe fonts — default fonts found in multiple operating systems and devices. However, if you want to add a creative touch to your email typography, you can use font embedding services like Google Fonts.
Some email clients show pictures by default, while others block them, which, among other things, affects the possibility of collecting statistics. As a rule, small transparent images called tracking pixels are used for this purpose. Meaning that if an email client blocks images, it becomes impossible to understand whether a user has opened the message.
Remember to include alt-text for all of your images — this will help the recipients understand what value this or that image adds to your message even if it cannot be displayed. Moreover, you can add style rules to the text for the tag, for example, color or font-family , which will be applied to the alt-text.
Step 1: Use HTML Tables for Layout
That’s right: tables are back, big time! Web standards may have become the norm for coding pages for display in web browsers, but this isn’t the Web, baby. A few email software clients are light years behind the eight-ball in terms of CSS support, which means we must resort to using tables for layout if we really want our newsletters to display consistently for every reader (see the reading list at the end of this article for some excellent resources on CSS support in mail clients).
The first step in creating an HTML email is to decide what kind of layout you want to use. For newsletters, single column and two-column layouts work best, because they control the natural chaos that results when a large amount of content is pushed into such a small space as an email. Single column email designs also make it easy to display well on phones and tablets.
Two-column emails also use a header and footer. Like a two-column web page, they typically use a narrow, side column to house features and links to more information, while the wider column holds the body content of the email. To get a two-column email layout to display well on a phone or tablet requires some code-fu, as you’ll see later in this article.
Promotional emails follow similar rules but contain much less in the way of content and links. They often include one or two messages, and sometimes make use of one big image with small explanatory text and some links below the image.
All of these email layout possibilities can be created easily, using HTML tables to divide up the space into rows and columns. In fact, using HTML tables is the only way to achieve a layout that will render consistently across different mail clients.
No matter how your email is designed, it’s important to remember the most important content should appear at or near the top of the email, so it is visible immediately when a reader opens your email. The top left of an email message is often the first place people look when they open an email.
- For a two-column layout, create one table each for the header, the two center content columns, and the footer — that’s three tables in all. Wrap these tables into another container table. Use the same approach for single-column layouts, but give the content table one column. This approach is especially suitable if the design of your email contains images that are broken up over multiple table cells. Otherwise, a single table with td rows for its header (with colspan=”2″ if the design uses two columns), content, and footer should display fine in all but Lotus Notes email software.
- Use the attributes within the table and td tags to control the table’s display. For example, setting border=”0″ , valign=”top” , align=”left” (or center , if that suits the design), cellpadding=”0″ , cellspacing=”0″ , and so on. This primarily helps older email clients to display the email in a (barely) acceptable way.
- Even if the design of your email doesn’t include a border around your table, you might find it helpful during development to set border=”1″ to help with the debugging of any problems that arise with the internal alignment of tr and td tags. Change it back to border=”0″ for testing and production.
While this approach might offend purists who prefer to code using the latest standards, it is the only viable approach at this point. But the fact that we’re using tables for layout doesn’t mean we need to resort to old-school methods entirely. For example, no matter how poorly Lotus Notes displays HTML email, you should never have to resort to using the font tag. And while Outlook 2007’s HTML rendering engine is less than perfect, it does display basic HTML tables just fine.
Создание писем без работы с кодом
В дополнение к 13 блокам, которые доступны в Stripo для создания обычных HTML-шаблонов, мы также предлагаем набор встроенных инструментов, позволяющих создавать интерактивные письма без навыков программирования:
- — предназначены для того, чтобы моментально перенаправлять пользователей в интересующую их часть письма без необходимости долго скроллить. Просто активируйте эту опцию и соедините два элемента письма, углубляться в HTML-код не понадобится; — при наведении курсора появляется новое изображение. Это экономит много драгоценного места и оживляет ваши email-маркетинговые кампании. Чтобы использовать ролловер, просто активируйте эту опцию после загрузки основного изображения и загрузите дополнительную картинку; , или CSS-анимация — кнопки меняют цвет при наведении курсора. Используйте этот эффект, чтобы сделать ваш адаптивный шаблон более динамичным и менее статичными. Чтобы использовать эту опцию, войдите в меню «Оформление» и далее во вкладку «Кнопка», где просто активируйте переключатель «Подсвечивать по наведению»; — возможность оценить вас непосредственно в письме повышает показатели отклика пользователей на 520%. При помощи Stripo вы можете добавлять эти формы/рейтинги в свой HTML-шаблон без навыков программирования. И главное — эти элементы безупречно отображаются во всех основных почтовых клиентах.
Около 100 писем с AMP-контентом
Мы знаем, насколько важны все эти метрики для ваших email-маркетинговых кампаний. И как мало у вас времени. Именно поэтому мы создали около 100 AMP-шаблонов, чтобы вы могли оценить всю мощь AMP, не прилагая при этом лишних усилий.
Что такое real-time/динамический контент? Это такой тип контента, который обновляется в письме в тот момент, когда получатель его открывает. То есть вы можете предоставлять клиентам исключительно свежую и актуальную информацию независимо от того, когда письмо будет открыто.
В сфере eCommerce можно сообщать подписчикам о фактическом количестве доступных единиц товара на складе: для этого достаточно всего лишь обновить нужную информацию в своих Google-документах. Технология AMP позволяет подтягивать в письма информацию из Google Docs.
VBA Code To Send Email From Excel With Workbook As Attachment
As I explain above, you can generally use early or late binding for purposes of accessing the Outlook Object Model from Excel. There are a couple of differences in the VBA code depending on the binding you’re using.
VBA Code To Send Email From Excel Using Early Binding
The following sample macro (Send_Email_Excel_Attachment_Early_Binding) sends an email message with the active workbook as an attachment. This VBA Sub procedure uses early binding. You can find the equivalent version (using late binding) below.
Line #1: Dim outlookApp As Outlook.Application
Line #2: Dim outlookMail As Outlook.MailItem
Line #3: Set outlookApp = New Outlook.Application
Line #4: Set outlookMail = outlookApp.CreateItem(olMailItem)
Lines #5 And #17: With outlookMail | End With
The consequence of using a With… End With statement is that the series of statements within the block (lines #6 to #16 below) work with the object referred to in the opening line (outlookMail). In other words, all of the following lines of code work with the email item represented by outlookMail.
Lines #6, #7 And #8: .To = “[email protected] ; [email protected] ; [email protected]” | .CC = “[email protected] ; [email protected] ; [email protected]” | .BCC = “[email protected] ; sample[email protected] ; [email protected]”
Line #9: .Subject = “How to send email from Excel with Workbook as attachment using VBA”
Line #10: .BodyFormat = olFormatHTML
Line #11: .HTMLBody = “Hi,
I ‘m sending this message from Excel using VBA.
Please find a sample Excel workbook attached.”
Line #12: .Attachments.Add ActiveWorkbook.FullName
In this particular case, the VBA code uses a single parameter: Source. Source represents the source of the attachment and, in this line #12, is “ActiveWorkbook.FullName”. This way of specifying the source relies on the following 2 properties:
Line #13: .DeferredDeliveryTime = “8/8/2016 10:00:00 AM”
Line #14: .Importance = olImportanceHigh
In the sample Send_Email_Excel_Attachment_Early_Binding macro, the Importance property is set to olImportanceHigh. This particular value of the OlImportance enumeration means that the email is marked as high importance.
Line #15: .ReadReceiptRequested = True
Line #16: .Send
If you want to check out the email draft before sending it, you can replace the Send method with the MailItem.Display method. The consequence of using the Display method is that Outlook shows you the email draft for review, instead of sending it automatically.
Lines #18 And #19: Set outlookMail = Nothing | Set outlookApp = Nothing
VBA Code To Send Email From Excel Using Late Binding
Notice that the sample Send_Email_Excel_Attachment_Late_Binding macro above is almost identical to the Send_Email_Excel_Attachment_Early_Binding example above. The following image shows the only coding differences between both Sub procedures:
Lines #1 And #2: Dim outlookApp As Object | Dim outlookMail As Object
Both lines of code use the Dim statement to declare an object variable (outlookApp and outlookMail) As Object. As I explain above, declaring an object variable As Object forces late binding.
These lines of code are substantially the same as lines #1 and #2 of the macro example that uses early binding (Send_Email_Excel_Attachment_Early_Binding). The difference is the type that I use:
Line #3: Set outlookApp = CreateObject(“Outlook.Application”)
Therefore, it (i) creates a new Outlook instance and (ii) assigns this object reference to the outlookApp object variable. In both cases the object reference is to the new instance of the Outlook application.
- The main purpose of the CreateObject function is to create and return a reference to an ActiveX object. An ActiveX object is “an object that is exposed to other applications or programming tools through Automation interfaces”.
Macro Examples To Send Email From Excel Using Outlook In Practice
The email Outlook sends looks the same in both (early and late binding) cases. The only difference is the fact that the attachment changes (I stored the sample macros in separate workbooks).
Resources:
https://www.campaignmonitor.com/dev-resources/guides/coding-html-emails/
https://sendpulse.com/blog/coding-emails
https://www.sitepoint.com/how-to-code-html-email-newsletters/
https://stripo.email/templates/
https://powerspreadsheets.com/send-email-excel-vba/