通过PHP在电子邮件中发送HTML

80

如何使用PHP发送带图片的HTML格式电子邮件?

我想要一个包含一些设置和HTML输出的页面,并通过电子邮件发送到某个地址。我该怎么做?

主要的问题是如何附加文件。我应该怎么做?


你的问题是发送 HTML 代码吗?还是总的来说使用 PHP 发送电子邮件? - Adi
8个回答

178

这很简单。把图片留在服务器上,然后将 PHP + CSS 发送给它们...

$to = 'bob@example.com';

$subject = 'Website Change Request';

$headers  = "From: " . strip_tags($_POST['req-email']) . "\r\n";
$headers .= "Reply-To: " . strip_tags($_POST['req-email']) . "\r\n";
$headers .= "CC: susan@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

$message = '<p><strong>This is strong text</strong> while this is not.</p>';


mail($to, $subject, $message, $headers);

这一行代码告诉邮件发送者和接收者,这封电子邮件(希望如此)包含格式良好的HTML代码需要解释:

$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

这里是我获取信息的链接... (链接)

但你需要考虑安全问题...


CSS格式、图片以及HTML文件所需的其他文件(如JS)怎么办? - Abadis
4
@UmerHayat 同意,但我们都得从某个地方开始,即使只是学习如何谷歌一些东西... - Chris
8
如果你用htmlhead或者body元素,会在遵循(X)HTML标准的基于Web的邮件系统中造成绝对的混乱。此外,如果发送HTML电子邮件,则绝不要发送比h2更大的标题级别,因为在页面上,您的电子邮件主题(在正确的系统上)将作为单个h1元素呈现。如果这听起来不太清楚,请记住,Google试图将您的页面解释为报纸,其中只有一个主标题(例如,“我们赢得了战争!”)和许多较小的标题(例如,“被恶意麋鹿救出的小猫”)。 - John
5
这段文字中有一个错字 "$message .= ",这个变量之前没有声明过。 - madlopt
使用以下代码来将文本中的\r\n替换为\n:text = text.replace('\r\n', '\n')这将把所有Windows风格的换行符替换为Unix风格的换行符。 - luky
显示剩余2条评论

20

您需要使用图像的绝对路径编写HTML内容。在这里,绝对路径指的是您必须将图像上传到服务器,并在图像的src属性中提供直接路径,例如:<img src="http://yourdomain.com/images/example.jpg">

以下是PHP代码,供您参考。它来自于mail

<?php
    // Multiple recipients
    $to  = 'aidan@example.com' . ', '; // Note the comma
    $to .= 'wez@example.com';

    // Subject
    $subject = 'Birthday Reminders for August';

    // Message
    $message = '
      <p>Here are the birthdays upcoming in August!</p>
    ';

    // To send HTML mail, the Content-type header must be set
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";

    // Additional headers
    $headers .= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' . "\r\n";
    $headers .= 'From: Birthday Reminder <birthday@example.com>' . "\r\n";


    // Mail it
    mail($to, $subject, $message, $headers);
?>

你的问题解决了我的难题,感谢你的细心! - Jesse

13

我有这段代码,它在我的网站上可以完美运行:

public function forgotpassword($pass, $name, $to)
{
    $body  = "<table width=100% border=0><tr><td>";
    $body .= "<img width=200 src='";
    $body .= $this->imageUrl();
    $body .= "'></img></td><td style=position:absolute;left:350;top:60;><h2><font color = #346699>PMS Pvt Ltd.</font><h2></td></tr>";
    $body .= '<tr><td colspan=2><br/><br/><br/><strong>Dear '.$name.',</strong></td></tr>';
    $body .= '<tr><td colspan=2><br/><font size=3>As per Your request we send Your Password.</font><br/><br/>Password is : <b>'.$pass.'</b></td></tr>';
    $body .= '<tr><td colspan=2><br/>If you have any questions, please feel free to contact us at:<br/><a href="mailto:support@pms.com" target="_blank">support@pms.com</a></td></tr>';
    $body .= '<tr><td colspan=2><br/><br/>Best regards,<br>The PMS Team.</td></tr></table>';
    $subject = "Forgot Password";
    $this->sendmail($body, $to, $subject);
}

邮件函数

function sendmail($body, $to, $subject)
{
    //require_once 'init.php';

    $from = 'testing@gmail.com';
    $headersfrom = '';
    $headersfrom .= 'MIME-Version: 1.0' . "\r\n";
    $headersfrom .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headersfrom .= 'From: ' . $from . ' ' . "\r\n";
    mail($to, $subject, $body, $headersfrom);
}

如果需要更改图片,可以使用图像URL函数。只需更改一次该函数即可完成更改。我有很多邮件功能,例如忘记密码或创建用户等。因此,我正在使用图像URL函数。您可以直接设置路径。

function imageUrl()
{
    return "http://" . $_SERVER['SERVER_NAME'] . substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], "/") + 1) . "images/capacity.jpg";
}

@Jalpesh,那么对于CSS文件,您只需要做同样的事情吗?引用绝对路径,它应该可以工作,对吧? - Fernando Silva
1
@FernandoSilva 你需要设置绝对路径,并为元素设置类或ID,这样你的CSS才能起作用。 - Jalpesh Patel
@Jalpesh 我想我得尝试其他方法,因为Hotmail会删除所有浮动的CSS规则,而Gmail则会清除我的类。不确定是否有遗漏,但我的HTML已经准备好了数据,而CSS则负责布局。我正在使用PHPMailer类发送电子邮件,我找不到任何参考资料表明它是由此行为引起的,但我不确定。有什么建议要查看什么?另外,两者都可以通过内联样式正确显示图像。 - Fernando Silva

10
发送HTML邮件与使用PHP发送普通邮件并没有太大区别。需要添加的是PHP mail() 函数的头部参数中的内容类型。以下是一个示例。
<?php
    $to = "toEmail@domain.com";
    $subject = "HTML email";
    $message = "
    <html>
        <head>
            <title>HTML email</title>
        </head>

        <body>
            <p>A table as email</p>
            <table>
                <tr>
                    <th>Firstname</th>
                    <th>Lastname</th>
                </tr>
                <tr>
                    <td>Fname</td>
                    <td>Sname</td>
                </tr>
            </table>
        </body>
    </html>
    ";
    // Always set content-type when sending HTML email
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\b";
    $headers .= 'From: name' . "\r\n";
    mail($to, $subject, $message, $headers);
?>

你还可以查看这里,了解更详细的解释,由W3Schools提供。

6
您可以使用以下脚本通过PHP轻松发送包含HTML内容的电子邮件。
<?php
$to = 'user@example.com';
$subject = "Send HTML Email Using PHP";

$htmlContent = '
<html>
<body>
    <h1>Send HTML Email Using PHP</h1>
    <p>This is a HTMl email using PHP by CodexWorld</p>
</body>
</html>';

// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// Additional headers
$headers .= 'From: CodexWorld<info@codexworld.com>' . "\r\n";
$headers .= 'Cc: welcome@example.com' . "\r\n";
$headers .= 'Bcc: welcome2@example.com' . "\r\n";

// Send email
if(mail($to,$subject,$htmlContent,$headers)):
    $successMsg = 'Email has sent successfully.';
else:
    $errorMsg = 'Email sending fail.';
endif;
?>

源代码和现场演示可以在这里找到 - 使用PHP发送美观的HTML电子邮件


3

关于“一个写得很好的教程”:据称这是你写的。值得披露吗? - Peter Mortensen

2
最简单的方法可能就是使用Zend Framework或其他框架,如CakePHPSymfony
您也可以使用标准的mail函数,但需要更多关于如何附加图片的知识。
另外,您可以将图像托管在服务器上而不是附加它们。发送HTML邮件的文档记录在mail()函数文档中。

@gonatee 取决于您想要的质量水平。被接受的答案并不适用于除了最基本情况以外的所有情况。如果您只需要基本情况,那么使用 mail() 就可以了。如果您需要更可靠的解决方案或者有复杂的情况或需求,最好依赖于已经通过数十个 RFC 文档和多年的错误修复的框架或库。如果您能找到一个专门的库或框架,让您选择所需的功能,那么没有理由依赖于自己来解决所有问题。 - Martijn

1

在构建HTML正文时,关键是要知道图像MIME部分的内容id。

简而言之,就是使img标签为—<img src="cid:输入内容id" />

Kronolith.php

请查看函数buildMimeMessage以获取一个可工作的示例。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接