Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

php发邮件类 附件

作者:花小泽ノ   发布日期:2025-12-02   浏览:918

以下是一个使用PHP发送带有附件的邮件的示例代码:

<?php
$to = 'recipient@example.com';
$subject = 'Test Email with Attachment';
$message = 'This is a test email with attachment.';

$from = 'sender@example.com';
$replyTo = 'sender@example.com';

$attachmentPath = '/path/to/attachment.pdf';
$attachmentName = 'attachment.pdf';

// 邮件头部信息
$headers = "From: $from\r\n";
$headers .= "Reply-To: $replyTo\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"boundary\"\r\n";

// 邮件内容
$body = "--boundary\r\n";
$body .= "Content-Type: text/plain; charset=\"utf-8\"\r\n";
$body .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$body .= $message."\r\n\r\n";

// 附件
$fileContent = file_get_contents($attachmentPath);
$body .= "--boundary\r\n";
$body .= "Content-Type: application/octet-stream; name=\"$attachmentName\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "Content-Disposition: attachment; filename=\"$attachmentName\"\r\n\r\n";
$body .= chunk_split(base64_encode($fileContent))."\r\n";
$body .= "--boundary--";

// 发送邮件
if (mail($to, $subject, $body, $headers)) {
    echo 'Email sent successfully.';
} else {
    echo 'Error sending email.';
}
?>

请将$to变量设置为收件人的电子邮件地址,将$from$replyTo变量设置为发件人的电子邮件地址。将$attachmentPath变量设置为附件的文件路径,将$attachmentName变量设置为附件的文件名。

这个示例代码假设您的PHP环境已正确配置以发送电子邮件。请注意,某些托管提供商可能对发送邮件的限制,或者您可能需要配置SMTP服务器来发送邮件。

上一篇:php命令行异步

下一篇:php 分享微信好友

大家都在看

php session用法

php 定义常量

phpisset函数

php html转图片

php后端

php爬虫框架

php读取csv文件

php+mysql动态网站开发

phpmyadmin docker

php session id

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站