php - 如何在 PHP 中发送带有附件的邮件
问题描述
我想用 PHP 发送带有附件的邮件。我从一个网站尝试了这个例子:
//recipient
$to = 'my email adress';
//sender
$from = 'test@example.com';
$fromName = 'Moduleingabe';
//email subject
$subject = 'test email';
//attachment file path
$file = $dateiname;
//email body content
$htmlContent = '<h1>Test email</h1>
<p>This email has sent from PHP script with attachment.</p>';
//header for sender info
$headers = "From: $fromName"." <".$from.">";
//boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
//headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
//multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
//preparing attachment
if(!empty($file) > 0){
if(is_file($file)){
$message .= "--{$mime_boundary}\n";
$fp = @fopen($file,"rb");
$data = @fread($fp,filesize($file));
@fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($file)."\"\n" .
"Content-Description: ".basename($file)."\n" .
"Content-Disposition: attachment;\n" . "
filename=\"".basename($file)."\"; size=".filesize($file).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $from;
//send email
$mail = @mail($to, $subject, $message, $headers, $returnpath);
//email sending status
echo $mail?"<h1>Mail sent.</h1>":"<h1>Mail sending failed.</h1>";
这给了我结果Mail sending failed.
,我也尝试了mail()
没有附件的函数,它给了我一个false
.
我尝试使用我拥有的真实邮件地址$from
,但它给了我相同的结果,尽管我记得当我第一次尝试该功能时能够使用任何示例邮件。
解决方案
在我的服务器上尝试您的代码。
https://files.olivierlam.fr/test/mail.php?to=YOUREMAIL&from=EMAILSENDER
它对我有用。我已收到电子邮件。它显示已发送的邮件。
推荐阅读
- python - Selenium 在同一网站上打开了数千个链接,被 Captcha 检测到
- git - 如何使用 git 更新应用程序的 200 个实例
- python - 我不明白 plt.show()... 做了什么
- forms - 在后端使用 DOMPurify 来清理表单数据的错误?
- mysql - MySQL 更新不支持索引条件下推?
- javascript - 在 php 中定义一个外部 javascript 函数
- ubuntu - 为什么 Eclipse (Neon) 不会在 Linux 中启动?
- html - CSS重置边距问题。我无法摆脱边距
- python - systemd - 作为 systemd 服务运行时,python 脚本不旋转日志文件
- c - ARM 汇编:如何交换数组元素以实现排序?