我正准备为网站创建一个表单页面,该页面需要用户填写许多字段,并将其发送到指定的电子邮件。我能够成功发送电子邮件,但邮件中找不到附件。
$model->attributes=$_POST['ContactForm'];
if($model->validate())
{
require("class.phpmailer.php");
$mail = new PhpMailer;
$mail->IsSMTP();
$mail->SMTPSecure = "ssl";
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->SMTPSecure = true;
$mail->Username = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3a0bcbeb6b2b7b7a1b6a0a093b4beb2babffdb0bcbe" rel="noreferrer noopener nofollow">[email protected]</a>';
$mail->Port = '465';
$mail->Password = '*****';
$mail->SMTPKeepAlive = true;
$mail->Mailer = "smtp";
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true;
$mail->CharSet = 'utf-8';
$mail->SMTPDebug = 0;
$mail->SetFrom('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6204100d0f03060622050f030b0e4c010d0f" rel="noreferrer noopener nofollow">[email protected]</a>', 'name');
$mail->Subject = $_POST['ContactForm']['subject'];
$mail->AltBody = 'To view the message, please use an HTML compatible';
$mail->MsgHTML($_POST['ContactForm']['body']);
$mail->AddAttachment($_POST['ContactForm']['filename']); /**Problem is here */
}
我也尝试将 $_POST 更改为 $_FILES 以添加附件。
我的看法:
<?php $form=$this->beginWidget('CActiveForm', array(
'htmlOptions' => array('enctype' => 'multipart/form-data') ,
)); ?>
<?php echo $form->fileField($model, 'filename');?>
<?php echo $form->error($model, 'filename');?>
最佳答案
由于您正在使用 yii。所以让我们以 yii 风格来做吧。
首先为上传的文件创建一个对象
$attachment=CUploadedFile::getInstance($model, 'filename');
if($attachment !== null){
$path= $attachment->tempName;
$name=$attachment->name;
}
// then do the coding for you mail and change this line
$mail->AddAttachment($path,$name);
关于php - 使用 PHPMailer 在邮件中添加附件失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22856655/