Codeigniter发送带附件的电子邮件

15

我正在尝试使用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();
9个回答

28

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

    }

你能帮我找出我在这里做错了什么吗?http://stackoverflow.com/questions/43676702/send-mail-with-codeignitor-email-libray。谢谢。 - G B
我找到了一篇文章,描述了如何使用SMTP在CodeIgniter应用程序中发送电子邮件。使用众所周知和维护良好的电子邮件发送类。https://www.cloudways.com/blog/send-email-codeigniter-smtp/ - Owais Alam
你如何动态地附加文件?我的意思是,如果我想在不同的情况下附加不同的文件,你会怎么做? - julie
每次都需要从数据库中获取文件名 @julie - Bergin
@nitheesh-k-p 你好!那个文件应该放在哪个安全路径下?我不希望别人猜测文件名,然后从资产文件夹中下载它。 - gepex

5

我之前也遇到过这个问题,是由于文件路径的问题。所以我将路径更改为:


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


这样就可以正常工作了。


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>

我已经修改了system/libraries/Email中第725行的内容,原来为

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

请提供需要翻译的具体内容。
'content'       => "\r\n" . chunk_split(base64_encode($file_content)),<br>

这对我来说有效,但并非完美的解决方案。


非常感谢,我一直在寻找使用Gmail发送电子邮件附件而不是其他邮件客户端的解决方案。我知道这一定是一些小问题。CI必须在某个阶段解决它。 - Mike C

2
尝试在 $ci->email->attach() 中放置完整路径。
在Windows中,这应该是类似于:
$ci->email->attach('d:/www/website/test/myfile.pdf');

这种方法在过去对我非常有效。

1
如果您想在电子邮件中发送附件,而不需要将文件上传到服务器,请参考以下步骤。
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();

0

使用路径助手

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

在电子邮件行

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

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!";
                }

0

这里是完整的源代码

    $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);
    }

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接