繁体   English   中英

Codeigniter 发送带有附件的电子邮件

[英]Codeigniter send email with attach file

我正在尝试使用附件文件在 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();

$this->email->attach()

使您能够发送附件。 将文件路径/名称放在第一个参数中。 注意:使用文件路径,而不是 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());
        }

    }

我以前遇到过这个问题,路径文件的问题,所以我将路径文件更改为


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


它对我来说很好用

使用 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>

我将 system/libraries/Email 中的第 725 行从

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


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

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

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

在 Windows 上,这会类似于

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

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

使用路径助手

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

在电子邮件线上

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

在这里我使用 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!";
                }

这是完整的源代码

    $validation_rules = array(
        array('field' => 'name', 'rules' => COMMON_RULES),
        array('field' => 'email', 'rules' => COMMON_RULES),
        array('field' => 'message', 'rules' => COMMON_RULES),
    );

    $this->validation_errors($validation_rules);

    $name = $this->input->post('name');
    $email = $this->input->post('email');
    $message = $this->input->post('message');

    $this->load->library('email');

    //upload file
    $attachment_file = "";
    if (!empty($_FILES) && isset($_FILES["attachment_file"])) {

        $image_name = $_FILES["attachment_file"]['name'];

        $ext = pathinfo($image_name, PATHINFO_EXTENSION);

        $new_name = time() . '_' . $this->get_random_string();

        $config['file_name'] = $new_name . $ext;
        $config['upload_path'] = "uploads/email/";
        $config['allowed_types'] = "*";

        $this->load->library('upload', $config);
        $this->upload->initialize($config);

        if ($this->upload->do_upload('attachment_file')) {

            $finfo = $this->upload->data();
            $attachment_file = base_url() . 'uploads/email/' . $finfo['file_name'];
        } else {

            $error = $this->upload->display_errors();
            $this->msg = $error;
            $this->_sendResponse(5);
        }
    }

    $this->email->from($email, "$name")
            ->to("example@gmail.com")
            ->subject("FeedBack From $name")
            ->message($message)
            ->attach($attachment_file);

    if ($this->email->send()) {

        // temp pass updated.
        $this->msg = "Email send successfully.";
        $this->_sendResponse(1);
    } else {

        $this->msg = "Internal server error/Something went wrong.";
        $this->_sendResponse(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();
 $this->load->library('email'); // Loading the email library.
 $this->email->clear(TRUE);
 $this->email->from($user_email, $name);
 $this->email->to('email@gmail.com');
 $this->email->subject("Some subject");
 $this->email->message("Some message");
 if($_FILES['userfile']['name']!='' && $_FILES['userfile'['size'] > 0){
     $attach_path = $_FILES['userfile']['tmp_name'];
     $attach_name = $_FILES['userfile']['name'];
     $this->email->attach($attach_path,'attachment',$attach_name);
}
$this->email->send();

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

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();


}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM