php - 使用 PHPMailer 在邮件中添加附件失败

标签 php email yii phpmailer

我正准备为网站创建一个表单页面,该页面需要用户填写许多字段,并将其发送到指定的电子邮件。我能够成功发送电子邮件,但邮件中找不到附件。

$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/

相关文章:

html - 使用 Google Apps 脚本在电子邮件正文中将 Google Doc 作为 HTML 发送,同时保留格式

C# yandex 邮件发送错误 5.5.4 错误 : send AUTH command first

php - 在 Yii 供应商中安装 fpdf

php - 如何使一对列在mysql中唯一

PHP - 多语言应用程序设计

php - 如何在我的电子邮件模板中使用从数据库中获取的变量值

css - 是什么设置了 Yii2 的 DetailView 中的列宽/分布?

php - 表不显示数组查询中的任何结果

带有特殊字符的php mysql搜索

javascript - Yii+datepicker boostrap 如何更新网格