Asked  8 Months ago    Answers:  5   Viewed   40 times

I am trying to send email on codeigniter with attach file.

I always receive email successfully. However , I never receive with attach file. Below is code and highly appreciate for all comments.

    $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'] = "rn";

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

 Answers

75

$this->email->attach()

Enables you to send an attachment. Put the file path/name in the first parameter. Note: Use a file path, not a URL. For multiple attachments use the function multiple times. For example:

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("rn");
          $this->email->from('abc@gmail.com');
          $this->email->to($email);
          $this->email->subject($subject);
          $this->email->message($message);
            $this->email->attach('C:UsersxyzDesktopimagesabc.png');
          if($this->email->send())
         {
          echo 'Email send.';
         }
         else
        {
         show_error($this->email->print_debugger());
        }

    }
Wednesday, March 31, 2021
 
BetaRide
answered 8 Months ago
76

Found this code as one of the first hits of the google://pear mail attachment search.

include('Mail.php');
include('Mail/mime.php');

$text = 'Text version of email';
$html = '<html><body>HTML version of email</body></html>';
$file = './files/example.zip';
$hdrs = array(
              'From'    => 'someone@domain.pl',
              'To'      => 'someone@domain.pl',
              'Subject' => 'Test mime message'
              );

$mime = new Mail_mime();

$mime->setTXTBody($text);
$mime->setHTMLBody($html);

$mime->addAttachment($file,'application/octet-stream');

$body = $mime->get();
$hdrs = $mime->headers($hdrs);

$mail =& Mail::factory('mail', $params);
$mail->send('mail@domain.pl', $hdrs, $body); 
Wednesday, March 31, 2021
 
ericstumper
answered 8 Months ago
34

Currently there is no easy way in ZF2 (2.2) to combine a multipart/alternative body (html with text alternative for clients that cannot/do-not-want-to use html) with attachments. If you add the 'multipart/alternative' content-type header to the entire message, in some email clients the attachment (link) will not be displayed.

The solution is to split the message in two, the body (text and html) and the attachment:

http://jw-dev.blogspot.com.es/2013/01/zf2-zend-mail-multipartalternative-and.html

an example:

        $content  = new MimeMessage();
        $htmlPart = new MimePart("<html><body><p>Sorry,</p><p>I'm going to be late today!</p></body></html>");
        $htmlPart->type = 'text/html';
        $textPart = new MimePart("Sorry, I'm going to be late today!");
        $textPart->type = 'text/plain';
        $content->setParts(array($textPart, $htmlPart));

        $contentPart = new MimePart($content->generateMessage());        
        $contentPart->type = 'multipart/alternative;' . PHP_EOL . ' boundary="' . $content->getMime()->boundary() . '"';

        $attachment = new MimePart(fopen('/path/to/test.pdf', 'r'));
        $attachment->type = 'application/pdf';
        $attachment->encoding    = Mime::ENCODING_BASE64;
        $attachment->disposition = Mime::DISPOSITION_ATTACHMENT;

        $body = new MimeMessage();
        $body->setParts(array($contentPart, $attachment));

        $message = new Message();
        $message->setEncoding('utf-8')
        ->addTo('mywife@home.com')
        ->addFrom('myself@office.com')
        ->setSubject('will be late')
        ->setBody($body);

        $transport = new SmtpTransport();
        $options   = new SmtpOptions($transportConfig),
        ));

        $transport->setOptions($options);
        $transport->send($message);

For the above you would need the following use statements:

use ZendMailMessage;
use ZendMailTransportSmtp as SmtpTransport;
use ZendMailTransportSmtpOptions;
use ZendMimeMime;
use ZendMimePart as MimePart;
use ZendMimeMessage as MimeMessage;

ZF1 had a _buildBody() method in Zend_Mail_Transport_Abstract which did this automatically.

Saturday, May 29, 2021
 
danjah
answered 5 Months ago
81

$sender_lname = filter_var($_POST["fname"], FILTER_SANITIZE_STRING); Should be, $sender_lname = filter_var($_POST["lname"], FILTER_SANITIZE_STRING);

If you are refreshing a browser, they tend to cache the last POST request. You may be asked if you want to re-submit form data. Try adding a hidden field with a hash value for a token.

<input type="hidden" name="token" value="someHashValue">

Implement sessions to compare the submitted token against the one stored in $_SESSION.

session_start();
session_regenerate_id(); //Used properly, helps deter session fixation;
$_SESSION['token'] = "someHashValue"; //Must be unique for each page load.

Use a good hashing function to create the token. I would steer clear of md5 and sha1.

Basically...

if($_SESSION['token'] === $_POST['token'])
{
    //Good. You want to filter, validate, and check this early on.
    //Whatever you do, just be consistent.
}

Also, be wary of using the file name ($file_name = $_FILES['file_upload']['name'];) supplied by the browser in your code. Most would say find a way not to use it, but if you do, you still need to filter and validate it in some way. Re-naming the file might be appropriate. Checking the file size is a good idea, too. Don't rely too heavily on the php.ini on the file size bit. If file type matters, you can even try to inspect the file before accepting it.

Lastly, when you get there, if you are going to use PHP filter functions, it may be a good idea to use filter_input_array() with INPUT_POST for your POST data. For the $_FILES superglobal, I made a separate routine just for validating it (but, you cannot use filter_input_array() for that). Good luck! You are on your way!

Saturday, May 29, 2021
 
Trott
answered 5 Months ago
72

Explicitly filling in the ContentDisposition fields did the trick.

if (attachmentFilename != null)
{
    Attachment attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);
    ContentDisposition disposition = attachment.ContentDisposition;
    disposition.CreationDate = File.GetCreationTime(attachmentFilename);
    disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
    disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
    disposition.FileName = Path.GetFileName(attachmentFilename);
    disposition.Size = new FileInfo(attachmentFilename).Length;
    disposition.DispositionType = DispositionTypeNames.Attachment;
    message.Attachments.Add(attachment);                
}

BTW, in case of Gmail, you may have some exceptions about ssl secure or even port!

smtpClient.EnableSsl = true;
smtpClient.Port = 587;
Wednesday, June 2, 2021
 
Tucker
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share