帶附件郵件採用 multipart/mixed 結構,包含:
text/plain 或 text/html)application/octet-stream 或具體 MIME 類型),Base64 編碼class MailWithAttachment {
private string $boundary;
private array $parts = [];
private array $headers = [];
public function __construct() {
$this->boundary = '==MULTIPART_' . md5(microtime() . random_bytes(16)) . '==';
$this->headers['MIME-Version'] = '1.0';
$this->headers['Content-Type'] = "multipart/mixed; boundary=\"{$this->boundary}\"";
}
public function setFrom(string $email, string $name = ''): self {
$this->headers['From'] = $name ? "{$name} <{$email}>" : $email;
$this->headers['Return-Path'] = $email;
$this->headers['Reply-To'] = $email;
return $this;
}
public function setTo(string|array $emails): self {
$this->headers['To'] = is_array($emails) ? implode(', ', $emails) : $emails;
return $this;
}
public function setSubject(string $subject): self {
$this->headers['Subject'] = '=?UTF-8?B?' . base64_encode($subject) . '?=';
return $this;
}
public function setTextBody(string $text): self {
$this->addPart($text, 'text/plain; charset=UTF-8');
return $this;
}
public function setHtmlBody(string $html): self {
$this->addPart($html, 'text/html; charset=UTF-8');
return $this;
}
public function addAttachment(string $filePath, string $fileName = '', string $mimeType = ''): self {
if (!is_readable($filePath)) {
throw new InvalidArgumentException("檔案不可讀:$filePath");
}
$fileName = $fileName ?: basename($filePath);
$mimeType = $mimeType ?: mime_content_type($filePath) ?: 'application/octet-stream';
$content = chunk_split(base64_encode(file_get_contents($filePath)));
$partHeaders = [
'Content-Type' => "{$mimeType}; name=\"{$fileName}\"",
'Content-Transfer-Encoding' => 'base64',
'Content-Disposition' => "attachment; filename=\"{$fileName}\"",
];
$this->parts[] = [$partHeaders, $content];
return $this;
}
private function addPart(string $content, string $contentType): void {
$this->parts[] = [
['Content-Type' => $contentType, 'Content-Transfer-Encoding' => '8bit'],
$content
];
}
public function send(): bool {
$message = '';
foreach ($this->parts as [$partHeaders, $partBody]) {
$message .= "--{$this->boundary}\r\n";
foreach ($partHeaders as $k => $v) {
$message .= "{$k}: {$v}\r\n";
}
$message .= "\r\n{$partBody}\r\n";
}
$message .= "--{$this->boundary}--\r\n";
$headerStr = '';
foreach ($this->headers as $k => $v) {
$headerStr .= "{$k}: {$v}\r\n";
}
// 使用 PHP mail()(需本地 MTA:sendmail/postfix/exim)
return @mail($this->headers['To'], '', $message, $headerStr);
}
}
$mail = new MailWithAttachment();
$mail->setFrom('noreply@example.com', '系統通知')
->setTo('user@example.com')
->setSubject('您的月度報表')
->setHtmlBody('月度報表
請查收附件。
')
->addAttachment('/var/reports/monthly_202401.pdf', '月度報表_202401.pdf', 'application/pdf')
->addAttachment('/var/reports/data.xlsx', '原始數據.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
if ($mail->send()) {
echo '郵件發送成功';
} else {
echo '發送失敗,請檢查 mail.log';
}
原生 mail() 存在諸多限制:
composer require phpmailer/phpmailer)use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// SMTP 設定
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'sender@example.com';
$mail->Password = 'smtp_password';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // 或 SMTPS
$mail->Port = 587;
// 信件內容
$mail->setFrom('sender@example.com', '系統通知');
$mail->addAddress('user@example.com', '收件者');
$mail->Subject = '帶附件測試';
$mail->isHTML(true);
$mail->Body = 'HTML 內容
支援圖文並茂
';
$mail->AltBody = '純文字備用內容';
// 附件
$mail->addAttachment('/path/to/file.pdf', '重命名.pdf');
$mail->addAttachment('/path/to/image.png'); // 保留原名
// 內嵌圖片(HTML 中用
)
$mail->addEmbeddedImage('/path/to/logo.png', 'logo');
$mail->send();
echo '發送成功';
} catch (Exception $e) {
echo "發送失敗:{$mail->ErrorInfo}";
}
$mail->DKIM_domain = 'example.com';
$mail->DKIM_private = file_get_contents('/etc/dkim/private.key');
$mail->DKIM_selector = 'default';
$mail->DKIM_passphrase = ''; // 若私鑰有密碼
$mail->DKIM_identity = $mail->From;
// Laravel Job
class SendReportEmail implements ShouldQueue {
use Queueable, SerializesModels;
public $userId, $reportPath;
public function handle() {
$user = User::find($this->userId);
Mail::to($user->email)->send(new ReportMail($this->reportPath));
}
}
// 控制器
SendReportEmail::dispatch($userId, $reportPath);
keepAlive)理解 MIME 多部件結構有助於除錯,但生產環境強烈建議使用 PHPMailer 或 Symfony Mailer,配合 SMTP 服務商、DKIM、佇列機制,才能獲得可靠、可觀測、高送達率的郵件發送能力。