feat: responsive HTML email templates with DreamHost SMTP

- Add professional HTML email template matching CV aesthetic
- Implement multipart emails (HTML + plain text fallback)
- Configure DreamHost SMTP with SSL (port 465)
- Add "light only" color scheme for Gmail iOS compatibility
- Include Reply-To header for easy sender response
- Add email validation and integration tests
- Update .env.example with DreamHost/Gmail SMTP examples
- Add .env to .gitignore to protect credentials
- Document email template customization and dark mode approach
This commit is contained in:
juanatsap
2025-12-02 13:42:36 +00:00
parent 40733034ca
commit 41dbd77c2f
9 changed files with 1019 additions and 94 deletions
+203 -44
View File
@@ -3,11 +3,13 @@ package services
import (
"bytes"
"crypto/tls"
"encoding/base64"
"fmt"
"html/template"
htmltemplate "html/template"
"log"
"net/smtp"
"strings"
texttemplate "text/template"
"time"
)
@@ -102,7 +104,7 @@ func containsNewlines(s string) bool {
return strings.ContainsAny(s, "\r\n")
}
// SendContactForm sends a contact form email
// SendContactForm sends a contact form email with HTML and plain text versions
func (e *EmailService) SendContactForm(data *ContactFormData) error {
// Validate data
if err := data.Validate(); err != nil {
@@ -114,17 +116,17 @@ func (e *EmailService) SendContactForm(data *ContactFormData) error {
if data.Subject != "" {
subject += data.Subject
} else {
subject += "New Message"
subject += "New Message from " + data.Name
}
// Build email body
body, err := e.buildEmailBody(data)
// Build email bodies (HTML and plain text)
htmlBody, textBody, err := e.buildEmailBody(data)
if err != nil {
return fmt.Errorf("failed to build email body: %w", err)
}
// Send email
if err := e.sendEmail(subject, body); err != nil {
// Send multipart email
if err := e.sendMultipartEmail(subject, htmlBody, textBody, data.Email); err != nil {
return fmt.Errorf("failed to send email: %w", err)
}
@@ -134,37 +136,129 @@ func (e *EmailService) SendContactForm(data *ContactFormData) error {
return nil
}
// buildEmailBody creates the email body from template
func (e *EmailService) buildEmailBody(data *ContactFormData) (string, error) {
emailTemplate := `New contact form submission:
From: {{.Email}}
Name: {{if .Name}}{{.Name}}{{else}}Not provided{{end}}
Company: {{if .Company}}{{.Company}}{{else}}Not provided{{end}}
Subject: {{if .Subject}}{{.Subject}}{{else}}Not provided{{end}}
Message:
{{.Message}}
---
IP: {{.IP}}
Time: {{.Time.Format "2006-01-02 15:04:05 MST"}}
`
tmpl, err := template.New("contact").Parse(emailTemplate)
if err != nil {
return "", err
}
var body bytes.Buffer
if err := tmpl.Execute(&body, data); err != nil {
return "", err
}
return body.String(), nil
// emailTemplateData wraps ContactFormData with display-safe fields
type emailTemplateData struct {
Name string
Email string
Company string
Subject string
Message string
IP string
Time time.Time
}
// sendEmail sends an email using SMTP
// buildEmailBody creates both HTML and plain text email bodies
func (e *EmailService) buildEmailBody(data *ContactFormData) (htmlBody, textBody string, err error) {
// Prepare template data with safe defaults
tmplData := emailTemplateData{
Name: data.Name,
Email: data.Email,
Company: data.Company,
Subject: data.Subject,
Message: data.Message,
IP: data.IP,
Time: data.Time,
}
// Set defaults for empty fields
if tmplData.Name == "" {
tmplData.Name = "Not provided"
}
// Build HTML body
htmlTmpl, err := htmltemplate.New("contact-html").Parse(ContactEmailHTMLTemplate())
if err != nil {
return "", "", fmt.Errorf("failed to parse HTML template: %w", err)
}
var htmlBuf bytes.Buffer
if err := htmlTmpl.Execute(&htmlBuf, tmplData); err != nil {
return "", "", fmt.Errorf("failed to execute HTML template: %w", err)
}
// Build plain text body
textTmpl, err := texttemplate.New("contact-text").Parse(ContactEmailPlainTemplate())
if err != nil {
return "", "", fmt.Errorf("failed to parse text template: %w", err)
}
var textBuf bytes.Buffer
if err := textTmpl.Execute(&textBuf, tmplData); err != nil {
return "", "", fmt.Errorf("failed to execute text template: %w", err)
}
return htmlBuf.String(), textBuf.String(), nil
}
// sendMultipartEmail sends an email with both HTML and plain text parts
func (e *EmailService) sendMultipartEmail(subject, htmlBody, textBody, replyTo string) error {
// Validate config
if e.config.SMTPHost == "" || e.config.SMTPPort == "" {
return fmt.Errorf("SMTP configuration incomplete")
}
if e.config.SMTPUser == "" || e.config.SMTPPassword == "" {
return fmt.Errorf("SMTP credentials missing")
}
if e.config.ToEmail == "" {
return fmt.Errorf("recipient email not configured")
}
from := e.config.FromEmail
if from == "" {
from = e.config.SMTPUser
}
to := e.config.ToEmail
// Build multipart message
message := e.formatMultipartMessage(from, to, replyTo, subject, htmlBody, textBody)
// SMTP server address
addr := fmt.Sprintf("%s:%s", e.config.SMTPHost, e.config.SMTPPort)
// Setup authentication
auth := smtp.PlainAuth("", e.config.SMTPUser, e.config.SMTPPassword, e.config.SMTPHost)
// Connect to SMTP server with TLS
client, err := e.connectSMTP(addr)
if err != nil {
return fmt.Errorf("failed to connect to SMTP server: %w", err)
}
defer client.Close()
// Authenticate
if err = client.Auth(auth); err != nil {
return fmt.Errorf("SMTP authentication failed: %w", err)
}
// Set sender and recipient
if err = client.Mail(from); err != nil {
return fmt.Errorf("failed to set sender: %w", err)
}
if err = client.Rcpt(to); err != nil {
return fmt.Errorf("failed to set recipient: %w", err)
}
// Send message
w, err := client.Data()
if err != nil {
return fmt.Errorf("failed to get data writer: %w", err)
}
_, err = w.Write([]byte(message))
if err != nil {
return fmt.Errorf("failed to write message: %w", err)
}
err = w.Close()
if err != nil {
return fmt.Errorf("failed to close writer: %w", err)
}
return client.Quit()
}
// sendEmail sends an email using SMTP (plain text only - legacy)
func (e *EmailService) sendEmail(subject, body string) error {
// Validate config
if e.config.SMTPHost == "" || e.config.SMTPPort == "" {
@@ -233,18 +327,33 @@ func (e *EmailService) sendEmail(subject, body string) error {
// connectSMTP establishes an SMTP connection with TLS
func (e *EmailService) connectSMTP(addr string) (*smtp.Client, error) {
// Connect to server
client, err := smtp.Dial(addr)
if err != nil {
return nil, err
}
// Start TLS
tlsConfig := &tls.Config{
ServerName: e.config.SMTPHost,
MinVersion: tls.VersionTLS12,
}
// Port 465 uses implicit SSL (direct TLS connection)
// Port 587 uses STARTTLS (plain connection upgraded to TLS)
if e.config.SMTPPort == "465" {
// Implicit SSL: Connect with TLS from the start
conn, err := tls.Dial("tcp", addr, tlsConfig)
if err != nil {
return nil, fmt.Errorf("TLS dial failed: %w", err)
}
client, err := smtp.NewClient(conn, e.config.SMTPHost)
if err != nil {
conn.Close()
return nil, fmt.Errorf("SMTP client creation failed: %w", err)
}
return client, nil
}
// STARTTLS: Connect plain, then upgrade to TLS
client, err := smtp.Dial(addr)
if err != nil {
return nil, err
}
if err = client.StartTLS(tlsConfig); err != nil {
client.Close()
return nil, err
@@ -253,7 +362,57 @@ func (e *EmailService) connectSMTP(addr string) (*smtp.Client, error) {
return client, nil
}
// formatMessage formats an email message with proper headers
// formatMultipartMessage formats a multipart email with HTML and plain text
func (e *EmailService) formatMultipartMessage(from, to, replyTo, subject, htmlBody, textBody string) string {
// Generate boundary for multipart
boundary := fmt.Sprintf("----=_Part_%d", time.Now().UnixNano())
var message strings.Builder
// Headers
message.WriteString(fmt.Sprintf("From: %s\r\n", from))
message.WriteString(fmt.Sprintf("To: %s\r\n", to))
if replyTo != "" {
message.WriteString(fmt.Sprintf("Reply-To: %s\r\n", replyTo))
}
message.WriteString(fmt.Sprintf("Subject: %s\r\n", subject))
message.WriteString("MIME-Version: 1.0\r\n")
message.WriteString(fmt.Sprintf("Content-Type: multipart/alternative; boundary=\"%s\"\r\n", boundary))
message.WriteString(fmt.Sprintf("Date: %s\r\n", time.Now().Format(time.RFC1123Z)))
message.WriteString("\r\n")
// Plain text part
message.WriteString(fmt.Sprintf("--%s\r\n", boundary))
message.WriteString("Content-Type: text/plain; charset=\"utf-8\"\r\n")
message.WriteString("Content-Transfer-Encoding: quoted-printable\r\n")
message.WriteString("\r\n")
message.WriteString(textBody)
message.WriteString("\r\n")
// HTML part
message.WriteString(fmt.Sprintf("--%s\r\n", boundary))
message.WriteString("Content-Type: text/html; charset=\"utf-8\"\r\n")
message.WriteString("Content-Transfer-Encoding: base64\r\n")
message.WriteString("\r\n")
// Encode HTML as base64 for safe transmission
encoded := base64.StdEncoding.EncodeToString([]byte(htmlBody))
// Split into 76-character lines per RFC 2045
for i := 0; i < len(encoded); i += 76 {
end := i + 76
if end > len(encoded) {
end = len(encoded)
}
message.WriteString(encoded[i:end])
message.WriteString("\r\n")
}
// End boundary
message.WriteString(fmt.Sprintf("--%s--\r\n", boundary))
return message.String()
}
// formatMessage formats an email message with proper headers (plain text only)
func (e *EmailService) formatMessage(from, to, subject, body string) string {
headers := make(map[string]string)
headers["From"] = from
+360
View File
@@ -0,0 +1,360 @@
package services
// CVEmailTheme provides a custom Hermes theme matching the CV's aesthetic
// Features:
// - Clean, minimal design with professional typography
// - Green accent color (#27ae60) matching CV highlights
// - Bracket aesthetic { } for headers
// - Responsive layout for all devices
// - Dark mode support via @media queries
// CVThemeCSS returns the CSS for the CV email theme
func CVThemeCSS() string {
return `
/* CV Email Theme - Responsive & Clean */
/* Reset and Base */
body, html {
margin: 0;
padding: 0;
width: 100%;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Quicksand', Roboto, Helvetica, Arial, sans-serif;
line-height: 1.6;
color: #333333;
background-color: #f5f5f5;
}
/* Container */
.email-container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
.email-wrapper {
background-color: #ffffff;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
overflow: hidden;
}
/* Header */
.email-header {
background: linear-gradient(135deg, #2b2b2b 0%, #1a1a1a 100%);
padding: 30px 40px;
text-align: center;
}
.email-logo {
color: #ffffff;
font-size: 24px;
font-weight: 700;
letter-spacing: -0.5px;
margin: 0;
}
.email-logo .bracket {
color: #27ae60;
font-weight: 700;
}
/* Body */
.email-body {
padding: 40px;
}
.email-greeting {
font-size: 20px;
font-weight: 600;
color: #1a1a1a;
margin-bottom: 20px;
}
.email-intro {
font-size: 16px;
color: #444444;
margin-bottom: 30px;
line-height: 1.7;
}
/* Content Card */
.content-card {
background-color: #fafafa;
border-left: 4px solid #27ae60;
border-radius: 0 6px 6px 0;
padding: 25px;
margin: 25px 0;
}
.content-card-header {
font-size: 14px;
font-weight: 600;
color: #27ae60;
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: 15px;
}
/* Data Table */
.data-table {
width: 100%;
border-collapse: collapse;
}
.data-table tr {
border-bottom: 1px solid #eeeeee;
}
.data-table tr:last-child {
border-bottom: none;
}
.data-table td {
padding: 12px 0;
vertical-align: top;
}
.data-table .label {
font-weight: 600;
color: #666666;
width: 100px;
font-size: 13px;
text-transform: uppercase;
letter-spacing: 0.3px;
}
.data-table .value {
color: #333333;
font-size: 15px;
}
/* Message Box */
.message-box {
background-color: #ffffff;
border: 1px solid #e0e0e0;
border-radius: 6px;
padding: 20px;
margin-top: 15px;
font-size: 15px;
line-height: 1.7;
color: #333333;
white-space: pre-wrap;
}
/* Metadata */
.email-metadata {
margin-top: 30px;
padding-top: 20px;
border-top: 1px solid #eeeeee;
font-size: 12px;
color: #999999;
}
.email-metadata span {
display: inline-block;
margin-right: 20px;
}
/* Footer */
.email-footer {
background-color: #fafafa;
padding: 30px 40px;
text-align: center;
border-top: 1px solid #eeeeee;
}
.email-footer-text {
font-size: 13px;
color: #888888;
margin: 0;
}
.email-footer-link {
color: #27ae60;
text-decoration: none;
}
.email-footer-link:hover {
text-decoration: underline;
}
/* Bracket Decoration */
.bracket-wrap {
display: inline;
}
.bracket-wrap::before {
content: '{ ';
color: #27ae60;
font-weight: 700;
}
.bracket-wrap::after {
content: ' }';
color: #27ae60;
font-weight: 700;
}
/* Responsive */
@media only screen and (max-width: 600px) {
.email-container {
padding: 10px;
}
.email-header {
padding: 25px 20px;
}
.email-body {
padding: 25px 20px;
}
.email-footer {
padding: 20px;
}
.content-card {
padding: 20px 15px;
}
.data-table .label {
display: block;
padding-bottom: 4px;
}
.data-table .value {
display: block;
padding-bottom: 8px;
}
}
/* Dark Mode: Disabled via "light only" color-scheme meta tag
* Gmail iOS aggressively inverts colors in dark mode, ignoring CSS.
* Using "light only" forces consistent rendering across all clients.
* See: https://www.hteumeuleu.com/2021/emails-react-to-dark-mode/
*/
`
}
// ContactEmailHTMLTemplate returns the HTML template for contact form emails
// Note: Uses "light only" color scheme to prevent Gmail iOS dark mode from
// inverting colors unpredictably. This ensures consistent appearance across all clients.
func ContactEmailHTMLTemplate() string {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- Prevent Gmail dark mode color inversion -->
<meta name="color-scheme" content="light only">
<meta name="supported-color-schemes" content="light only">
<title>New Contact Form Message</title>
<style>
:root { color-scheme: light only; }
` + CVThemeCSS() + `
</style>
</head>
<body>
<div class="email-container">
<div class="email-wrapper">
<!-- Header -->
<div class="email-header">
<h1 class="email-logo"><span class="bracket">{</span> CV Contact <span class="bracket">}</span></h1>
</div>
<!-- Body -->
<div class="email-body">
<p class="email-greeting">New message received</p>
<p class="email-intro">
Someone has sent you a message through your CV contact form.
</p>
<!-- Contact Details Card -->
<div class="content-card">
<div class="content-card-header">Contact Details</div>
<table class="data-table">
<tr>
<td class="label">From</td>
<td class="value">{{.Name}}</td>
</tr>
<tr>
<td class="label">Email</td>
<td class="value"><a href="mailto:{{.Email}}" style="color: #27ae60; text-decoration: none;">{{.Email}}</a></td>
</tr>
{{if .Company}}
<tr>
<td class="label">Company</td>
<td class="value">{{.Company}}</td>
</tr>
{{end}}
{{if .Subject}}
<tr>
<td class="label">Subject</td>
<td class="value">{{.Subject}}</td>
</tr>
{{end}}
</table>
</div>
<!-- Message Card -->
<div class="content-card">
<div class="content-card-header">Message</div>
<div class="message-box">{{.Message}}</div>
</div>
<!-- Metadata -->
<div class="email-metadata">
<span>IP: {{.IP}}</span>
<span>Time: {{.Time.Format "Jan 02, 2006 at 15:04 MST"}}</span>
</div>
</div>
<!-- Footer -->
<div class="email-footer">
<p class="email-footer-text">
This email was sent from your CV contact form.<br>
<a href="https://juan.andres.morenorub.io" class="email-footer-link">juan.andres.morenorub.io</a>
</p>
</div>
</div>
</div>
</body>
</html>`
}
// ContactEmailPlainTemplate returns the plain text template for contact form emails
func ContactEmailPlainTemplate() string {
return `
═══════════════════════════════════════════════════════════════
{ CV CONTACT }
═══════════════════════════════════════════════════════════════
NEW MESSAGE RECEIVED
────────────────────────────────────────────────────────────────
CONTACT DETAILS
───────────────
From: {{.Name}}
Email: {{.Email}}
{{if .Company}}Company: {{.Company}}
{{end}}{{if .Subject}}Subject: {{.Subject}}
{{end}}
MESSAGE
───────────────
{{.Message}}
────────────────────────────────────────────────────────────────
IP: {{.IP}}
Time: {{.Time.Format "Jan 02, 2006 at 15:04 MST"}}
────────────────────────────────────────────────────────────────
Sent from: juan.andres.morenorub.io
═══════════════════════════════════════════════════════════════
`
}