我正在使用PHPMailer向两个不同的收件人发送两个不同的电子邮件。我要附加用户上传到两个电子邮件的多个文件。
现在,多文件附件适用于第一封邮件,但不适用于第二封邮件。
使用我当前的代码,文件仅附加到第一封邮件,而没有文件附加到第二封邮件:
// First e-mail to recipient 1
$mail = new PHPMailer;
$mail->setFrom('example@example.com');
$mail->addAddress('recipient1@example.com');
$mail->Subject = 'Subject';
$mail->isHTML(true);
$mail->Body = '...';
// Attach multiple files one by one
for ($ct = 0; $ct < count($_FILES['userfile']['tmp_name']); $ct++) {
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct]));
$filename = $_FILES['userfile']['name'][$ct];
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
$mail->addAttachment($uploadfile, $filename);
} else {
$msg .= 'Failed to move file to ' . $uploadfile;
}
}
$mail->send(); // I only wrote this once because as it turns out, it sends both of the mails
// Second e-mail to recipient 2
$mail = new PHPMailer;
$mail->setFrom('example@example.com');
$mail->addAddress('recipient2@example.com');
$mail->Subject = 'Subject';
$mail->isHTML(true);
$mail->Body = '...';
// Attach multiple files one by one
for ($ct = 0; $ct < count($_FILES['userfile']['tmp_name']); $ct++) {
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct]));
$filename = $_FILES['userfile']['name'][$ct];
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
$mail->addAttachment($uploadfile, $filename);
} else {
$msg .= 'Failed to move file to ' . $uploadfile;
}
}
然后我尝试不将整个功能复制到两个邮件中,而只添加
$mail->addAttachment($uploadfile, $filename);
到第二封电子邮件。但是,这只会添加第一个给定的文件,并且重复此行会使同一文件发送两次。
有什么想法如何将多个(在我的情况下为3个)文件附加到两个不同的电子邮件中?
答案 0 :(得分:1)
我解决了这样的问题:
// First e-mail to recipient 1
$mail = new PHPMailer;
$mail->setFrom('example@example.com');
$mail->addAddress('recipient1@example.com');
$mail->Subject = 'Subject';
$mail->isHTML(true);
$mail->Body = '...';
// Attach multiple files one by one
for ($ct = 0; $ct < count($_FILES['userfile']['tmp_name']); $ct++) {
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct]));
$filename = $_FILES['userfile']['name'][$ct];
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
$mail->addAttachment($uploadfile, $filename);
} else {
$msg .= 'Failed to move file to ' . $uploadfile;
}
}
// Altered e-mail to recipient 2
$mail->ClearAddresses(); // avoid recipient 1 getting this altered mail
$mail->addAddress('recipient2@example.com');
$mail->Subject = 'New subject overwriting the first one';
$mail->Body = 'New body overwriting the first one';
$mail->send(); // send both mails
这样,同一封邮件(包括附件)基本上会发送两次,但是会通过覆盖e进行一些更改。 G。主题和身体。
答案 1 :(得分:0)
在发送第一封邮件时,您已将上传的文件从临时存储区中移出,因此在第二次尝试中不再存在。
move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)
您需要先移动上传的文件,然后使用两次变量$uploadfile
。
您应该真正将所有这些功能放到一个函数中,这样您也不会重复自己。