无法使用PHPMailer在邮件中添加附件

时间:2014-04-04 07:46:51

标签: 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 = 'someaddress@gmail.com';
    $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('fromadd@gmail.com', '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');?>

2 个答案:

答案 0 :(得分:2)

因为你正在使用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);

答案 1 :(得分:0)

您无法使用

捕获文件
$_POST['']

你必须使用

$_FILES['']

您应该阅读此链接,然后一步一步地进行操作

http://www.w3schools.com/php/php_file_upload.asp