Codeigniter发送带附件的电子邮件

时间:2014-08-21 00:37:23

标签: php codeigniter email email-attachments

我正在尝试使用附件文件在codeigniter上发送电子邮件。

我总是成功收到电子邮件。但是,我从未收到过附件。以下是代码,非常感谢所有评论。

    $ci = get_instance();
    $ci->load->library('email');
    $config['protocol'] = "smtp";
    $config['smtp_host'] = "ssl://smtp.gmail.com";
    $config['smtp_port'] = "465";
    $config['smtp_user'] = "test@gmail.com";
    $config['smtp_pass'] = "test";
    $config['charset'] = "utf-8";
    $config['mailtype'] = "html";
    $config['newline'] = "\r\n";

    $ci->email->initialize($config);

    $ci->email->from('test@test.com', 'Test Email');
    $list = array('test2@gmail.com');
    $ci->email->to($list);
    $this->email->reply_to('my-email@gmail.com', 'Explendid Videos');
    $ci->email->subject('This is an email test');
    $ci->email->message('It is working. Great!');

    $ci->email->attach( '/test/myfile.pdf');
    $ci->email->send();

10 个答案:

答案 0 :(得分:20)

<强> $这 - &GT;的电子邮件 - &GT;附加()

允许您发送附件。将文件路径/名称放在第一个参数中。注意:使用文件路径,而不是URL。对于多个附件,请多次使用该功能。例如:

public function setemail()
{
$email="xyz@gmail.com";
$subject="some text";
$message="some text";
$this->sendEmail($email,$subject,$message);
}
public function sendEmail($email,$subject,$message)
    {

    $config = Array(
      'protocol' => 'smtp',
      'smtp_host' => 'ssl://smtp.googlemail.com',
      'smtp_port' => 465,
      'smtp_user' => 'abc@gmail.com', 
      'smtp_pass' => 'passwrd', 
      'mailtype' => 'html',
      'charset' => 'iso-8859-1',
      'wordwrap' => TRUE
    );


          $this->load->library('email', $config);
          $this->email->set_newline("\r\n");
          $this->email->from('abc@gmail.com');
          $this->email->to($email);
          $this->email->subject($subject);
          $this->email->message($message);
            $this->email->attach('C:\Users\xyz\Desktop\images\abc.png');
          if($this->email->send())
         {
          echo 'Email send.';
         }
         else
        {
         show_error($this->email->print_debugger());
        }

    }

答案 1 :(得分:3)

我之前有这个问题,路径文件的问题,所以我将路径文件更改为

$attched_file= $_SERVER["DOCUMENT_ROOT"]."/uploads/".$file_name; $this->email->attach($attched_file);

它适用于我

答案 2 :(得分:3)

使用Codeigniter 3.1.0我遇到了同样的问题。似乎缺少“\ r \ n”:

Content-Type: application/pdf; name="test.pdf"<br>
Content-Disposition: attachment;<br>
Content-Transfer-Encoding: base64<br>
JVBERi0xLjYNJeLjz9MNCjQzNyAwIG9iag08PC9MaW5lYXJpemVkIDEvTCA3OTUyMTYvTyA0Mzkv<br>
RSA2ODEwODcvTiA0L1QgNzk0ODA3L0ggWyA1NjQgMjYxXT4+DWVuZG9iag0gICAgICAgICAgICAg<br>

应该是:

Content-Type: application/pdf; name="test.pdf"<br>
Content-Disposition: attachment;<br>
Content-Transfer-Encoding: base64<br>
<br>
JVBERi0xLjYNJeLjz9MNCjQzNyAwIG9iag08PC9MaW5lYXJpemVkIDEvTCA3OTUyMTYvTyA0Mzkv<br>
RSA2ODEwODcvTiA0L1QgNzk0ODA3L0ggWyA1NjQgMjYxXT4+DWVuZG9iag0gICAgICAgICAgICAg<br>

我在系统/图书馆/电子邮件中更改了第725行

 'content'       => chunk_split(base64_encode($file_content)),<br>


'content'       => "\r\n" . chunk_split(base64_encode($file_content)),<br>

它对我有用,但不是完美的解决方法。

答案 3 :(得分:2)

尝试将完整路径放入$ ci-&gt; email-&gt; attach();

在Windows上,这就像是

$ci->email->attach('d:/www/website/test/myfile.pdf');

这种方法过去对我很有用。

答案 4 :(得分:0)

使用路径助手

$this->load->helper('path');
$path = set_realpath('./images/');

在电子邮件行

$this->email->attach($path . $your_file);

答案 5 :(得分:0)

这里我使用phpmailer发送邮件
这里的完整代码在下面提到

$this->load->library('My_phpmailer');
                $mail = new PHPMailer();
                $mailBody = "test mail comes here2";
                $body = $mailBody;
                $mail->IsSMTP(); // telling the class to use SMTP
                $mail->Host = "ssl://smtp.gmail.com"; // SMTP server
                $mail->SMTPDebug = 1;// enables SMTP debug information (for testing)
                // 1 = errors and messages
                // 2 = messages only
                $mail->SMTPAuth = true;// enable SMTP authentication
                $mail->Host = "ssl://smtp.gmail.com"; // sets the SMTP server
                $mail->Port = 465;// set the SMTP port for the GMAIL server
                $mail->Username = "YourAccountIdComesHere@gmail.com"; // SMTP account username
                $mail->Password = "PasswordComesHere";// SMTP account password
                $mail->SetFrom('SetFromId@gmail.com', 'From Name Here');
                $mail->AddReplyTo("SetReplyTo@gmail.com", "Reply To Name Here");
                $mail->Subject = "Mail send by php mailer";
                $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
                $mail->MsgHTML($body);
                $mail->AddAttachment($cdnStorage . '/' . $fileName);
                $address ='WhomeToSendMailId@gmail.com';
                $mail->AddAddress($address, "John Doe");
                if (!$mail->Send()) {
                    echo "Mailer Error: " . $mail->ErrorInfo;
                } else {
                    echo "Message sent!";
                }

答案 6 :(得分:0)

这是完整的源代码

def InceptionResBlock(block_input, num_filters):
    x1 = keras.layers.Conv2D(num_filters,(1,1),activation='relu',kernel_initializer='he_normal', padding='same')(block_input)
    x1 = keras.layers.BatchNormalization(epsilon=1e-06,  momentum=0.9, weights=None)(x1)

    x2 = keras.layers.Conv2D(num_filters,(1,1),activation='relu',kernel_initializer='he_normal', padding='same')(block_input)
    x2 = keras.layers.Conv2D(num_filters,(3,3),activation='relu',kernel_initializer='he_normal', padding='same')(x2)
    x2 = keras.layers.BatchNormalization(epsilon=1e-06,  momentum=0.9, weights=None)(x2)

    x3 = keras.layers.Conv2D(num_filters,(1,1),activation='relu',kernel_initializer='he_normal', padding='same')(block_input)
    x3 = keras.layers.Conv2D(num_filters,(3,3),activation='relu',kernel_initializer='he_normal', padding='same')(x3)
    x3 = keras.layers.BatchNormalization(epsilon=1e-06,  momentum=0.9, weights=None)(x3)
    x3 = keras.layers.Conv2D(num_filters,(3,3),activation='relu',kernel_initializer='he_normal', padding='same')(x3)
    x3 = keras.layers.BatchNormalization(epsilon=1e-06,  momentum=0.9, weights=None)(x3)

    # x = keras.layers.Concatenate()([x1, x2, x3])
    x = x1 + x2 + x3
    x = keras.layers.Conv2D(num_filters,(1,1),activation='relu',kernel_initializer='he_normal', padding='same')(x)   
    print(x1.shape, x2.shape,x3.shape,x.shape,block_input.shape,'\n-----------------------------\n')
    out = keras.layers.Add()([x, block_input])
    return out

答案 7 :(得分:0)

如果您想在电子邮件中发送附件无需在服务器上上传文件,请参考以下内容。

HTML 查看文件

echo form_input(array('type'=>'file','name'=>'attach_file','id'=>'attach_file','accept'=>'.pdf,.jpg,.jpeg,.png'));

控制器文件

echo '<pre>'; print_r($_FILES); 显示以下上传的数据。

[attach_file] => Array
(
    [name] => my_attachment_file.png
    [type] => image/png
    [tmp_name] => C:\wamp64\tmp\php3NOM.tmp
    [error] => 0
    [size] => 120853
)

我们将使用临时上传路径 [tmp_name] 上传附件,因为我们不想在服务器上上传附件文件。

$this->email->clear(TRUE); //any attachments in loop will be cleared.
$this->email->from('your@example.com', 'Your Name');
$this->email->to('someone@example.com');
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
//Check if there is an attachment
if ( $_FILES['attach_file']['name']!='' && $_FILES['attach_file']['size'] > 0 )
{
    $attach_path = $_FILES['attach_file']['tmp_name'];
    $attach_name = $_FILES['attach_file']['name'];
    $this->email->attach($attach_path,'attachment',$attach_name);
}
$this->email->send();

答案 8 :(得分:-1)

    <?php

  class Email extends CI_Controller
{
    public Function index();
{
  $config = Array(
          'protocol' => 'smtp',
          'smpt_host' => 'ssl://googlemail.com',
          'smtp_port' => 465,
          'smtp_user' => 'example@gmail.com',
          'smtp_pass' => 'yourpass'
           );
 $this->load->library('email', $config);
 $this->email->set_newline("\r\n");

 $this->email->from('example@gmail.com');
 $this->email->to('example@gmail.com');
 $this->email->subject('This is a test email sending');
 $this->email->message('This is some message, you can type your own');

 if($this->email->send()
{
    echo "Your email has been sent";
}else{
   show_error($this->email->print_debugger());
}

}


 ?>

答案 9 :(得分:-2)

这将帮助您发送带有附件的电子邮件

private function sendEmail()
{
  //Load email library
    $this->load->library('email');
    $this->load->helper('path');
    $path = set_realpath('./uploads/');
    //SMTP & mail configuration
    $config = array(
        'protocol'  => 'smtp',
        'smtp_host' => 'ssl://smtp.googlemail.com',
        'smtp_port' => 465,
        'smtp_user' => 'yourEmail@gmail.com',
        'smtp_pass' => 'yourPassword',
        'mailtype' => 'html',
        'charset' => 'iso-8859-1',
        'wordwrap' => TRUE
    );
    $this->email->initialize($config);
    $this->email->set_mailtype("html");
    $this->email->set_newline("\r\n");

    $this->email->to('yourEmail@gmail.com');
    $this->email->from($_POST['email'],$_POST['name']);
    $this->email->subject($_POST['subject']);
    $this->email->message($_POST['message']);
    foreach ($_FILES as $key => $file)
    {
        if ($file['error'] == 0)
        {
            $this->email->attach($file['tmp_name'], '', $file['name']);
        }
    }

    $this->email->send();


}