PHP函数中嵌入CSS实现带样式邮件发送的问题求助
Fixing CSS Styling in Your Email Render Function
Got it, let's get that email styling working! The core issue here is your render() function is only outputting plain text—we need to wrap that content in an HTML structure that includes your CSS styles, since email clients rely on HTML (and carefully applied CSS) for formatting.
First, let's fix the typo in your code ($text should be $txt) and add the CSS integration. Here's a modified version of your function:
public function render(){ $txt = $this->getText(); // Define your email CSS styles (or load from an external file) $emailCss = ' body { font-family: "Helvetica Neue", Arial, sans-serif; line-height: 1.7; color: #2d3748; margin: 0; padding: 20px; } .email-container { max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); padding: 20px; } .email-heading { color: #2b6cb0; border-bottom: 1px solid #e2e8f0; padding-bottom: 10px; margin-top: 0; } .email-footer { font-size: 0.875em; color: #718096; margin-top: 20px; padding-top: 10px; border-top: 1px solid #e2e8f0; } '; // Build the full HTML email structure with embedded CSS $htmlEmail = ' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style>' . $emailCss . '</style> </head> <body> <div class="email-container"> <h1 class="email-heading">Your Email Subject</h1> <div class="email-content">' . $txt . '</div> <div class="email-footer"> This email was sent from our system. Please do not reply directly. </div> </div> </body> </html> '; // Output the formatted HTML email echo $htmlEmail; die(); }
Key Notes:
- CSS Placement: We added an embedded
<style>block in the HTML<head>. For maximum compatibility with picky email clients (looking at you, Outlook), you might want to inline critical styles directly on HTML elements (e.g.,<div style="font-family: Arial;">). Tools like Premailer can automate this conversion. - External CSS Option: If you prefer to keep styles in a separate file, replace the hardcoded
$emailCsswith:$emailCss = file_get_contents(__DIR__ . '/path/to/email-styles.css'); - Email Delivery: When sending this rendered HTML via email, make sure to set the
Content-Typeheader totext/htmlso clients recognize it as formatted content. For example, using PHP'smail()function:// Capture the rendered HTML (since your function uses echo/die) ob_start(); $yourEmailObject->render(); $renderedContent = ob_get_clean(); // Set email headers $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=UTF-8\r\n"; // Send the email mail($recipientEmail, $subject, $renderedContent, $headers);
内容的提问来源于stack exchange,提问作者user13376840
相关产品推荐
相关产品推荐

