Email Class

CodeIgniter’s robust Email Class supports the following features:

  • Multiple Protocols: Mail, Sendmail, and SMTP
  • TLS and SSL Encryption for SMTP
  • Multiple recipients
  • CC and BCCs
  • HTML or Plaintext email
  • Attachments
  • Word wrapping
  • Priorities
  • BCC Batch Mode, enabling large email lists to be broken into smallBCC batches.
  • Email Debugging tools

Using the Email Library

Sending Email

Sending email is not only simple, but you can configure it on the fly orset your preferences in the app/Config/Email.php file.

Here is a basic example demonstrating how you might send email:

  1. $email = \Config\Services::email();
  2.  
  3. $email->setFrom('your@example.com', 'Your Name');
  4. $email->setTo('someone@example.com');
  5. $email->setCC('another@another-example.com');
  6. $email->setBCC('them@their-example.com');
  7.  
  8. $email->setSubject('Email Test');
  9. $email->setMessage('Testing the email class.');
  10.  
  11. $email->send();

Setting Email Preferences

There are 21 different preferences available to tailor how your emailmessages are sent. You can either set them manually as described here,or automatically via preferences stored in your config file, describedbelow:

Preferences are set by passing an array of preference values to theemail initialize method. Here is an example of how you might set somepreferences:

  1. $config['protocol'] = 'sendmail';
  2. $config['mailPath'] = '/usr/sbin/sendmail';
  3. $config['charset'] = 'iso-8859-1';
  4. $config['wordWrap'] = true;
  5.  
  6. $email->initialize($config);

Note

Most of the preferences have default values that will be usedif you do not set them.

Setting Email Preferences in a Config File

If you prefer not to set preferences using the above method, you caninstead put them into the config file. Simply open theapp/Config/Email.php file, and set your configs in theEmail properties. Then save the file and it will be used automatically.You will NOT need to use the $email->initialize() method ifyou set your preferences in the config file.

Email Preferences

The following is a list of all the preferences that can be set whensending email.

PreferenceDefault ValueOptionsDescription
userAgentCodeIgniterNoneThe “user agent”.
protocolmailmail, sendmail, or smtpThe mail sending protocol.
mailpath/usr/sbin/sendmailNoneThe server path to Sendmail.
SMTPHostNo DefaultNoneSMTP Server Address.
SMTPUserNo DefaultNoneSMTP Username.
SMTPPassNo DefaultNoneSMTP Password.
SMTPPort25NoneSMTP Port.
SMTPTimeout5NoneSMTP Timeout (in seconds).
SMTPKeepAliveFALSETRUE or FALSE (boolean)Enable persistent SMTP connections.
SMTPCryptoNo Defaulttls or sslSMTP Encryption
wordWrapTRUETRUE or FALSE (boolean)Enable word-wrap.
wrapChars76 Character count to wrap at.
mailTypetexttext or htmlType of mail. If you send HTML email you must send it as a complete webpage. Make sure you don’t have any relative links or relative imagepaths otherwise they will not work.
charsetutf-8 Character set (utf-8, iso-8859-1, etc.).
validateTRUETRUE or FALSE (boolean)Whether to validate the email address.
priority31, 2, 3, 4, 5Email Priority. 1 = highest. 5 = lowest. 3 = normal.
CRLF\n“\r\n” or “\n” or “\r”Newline character. (Use “\r\n” to comply with RFC 822).
newline\n“\r\n” or “\n” or “\r”Newline character. (Use “\r\n” to comply with RFC 822).
BCCBatchModeFALSETRUE or FALSE (boolean)Enable BCC Batch Mode.
BCCBatchSize200NoneNumber of emails in each BCC batch.
DSNFALSETRUE or FALSE (boolean)Enable notify message from server

Overriding Word Wrapping

If you have word wrapping enabled (recommended to comply with RFC 822)and you have a very long link in your email it can get wrapped too,causing it to become un-clickable by the person receiving it.CodeIgniter lets you manually override word wrapping within part of yourmessage like this:

  1. The text of your email that
  2. gets wrapped normally.
  3.  
  4. {unwrap}http://example.com/a_long_link_that_should_not_be_wrapped.html{/unwrap}
  5.  
  6. More text that will be
  7. wrapped normally.

Place the item you do not want word-wrapped between: {unwrap} {/unwrap}

Class Reference

  • CodeIgniter\Email\Email
    • setFrom($from[, $name = ''[, $returnPath = null]])

Parameters:

  1. - **$from** (_string_) From e-mail address
  2. - **$name** (_string_) From display name
  3. - **$returnPath** (_string_) Optional email address to redirect undelivered e-mail toReturns:

CodeIgniter\Email\Email instance (method chaining)Return type:CodeIgniter\Email\Email

Sets the email address and name of the person sending the email:

  1. $email->setFrom('you@example.com', 'Your Name');

You can also set a Return-Path, to help redirect undelivered mail:

  1. $email->setFrom('you@example.com', 'Your Name', 'returned_emails@example.com');

Note

Return-Path can’t be used if you’ve configured ‘smtp’ asyour protocol.

  • setReplyTo($replyto[, $name = ''])

Parameters:

  1. - **$replyto** (_string_) E-mail address for replies
  2. - **$name** (_string_) Display name for the reply-to e-mail addressReturns:

CodeIgniter\Email\Email instance (method chaining)Return type:CodeIgniter\Email\Email

Sets the reply-to address. If the information is not provided theinformation in the setFrom method is used. Example:

  1. $email->setReplyTo('you@example.com', 'Your Name');
  • setTo($to)

Parameters:

  1. - **$to** (_mixed_) Comma-delimited string or an array of e-mail addressesReturns:

CodeIgniter\Email\Email instance (method chaining)Return type:CodeIgniter\Email\Email

Sets the email address(s) of the recipient(s). Can be a single e-mail,a comma-delimited list or an array:

  1. $email->setTo('someone@example.com');
  1. $email->setTo('one@example.com, two@example.com, three@example.com');
  1. $email->setTo(['one@example.com', 'two@example.com', 'three@example.com']);
  • setCC($cc)

Parameters:

  1. - **$cc** (_mixed_) Comma-delimited string or an array of e-mail addressesReturns:

CodeIgniter\Email\Email instance (method chaining)Return type:CodeIgniter\Email\Email

Sets the CC email address(s). Just like the “to”, can be a single e-mail,a comma-delimited list or an array.

  • setBCC($bcc[, $limit = ''])

Parameters:

  1. - **$bcc** (_mixed_) Comma-delimited string or an array of e-mail addresses
  2. - **$limit** (_int_) Maximum number of e-mails to send per batchReturns:

CodeIgniter\Email\Email instance (method chaining)Return type:CodeIgniter\Email\Email

Sets the BCC email address(s). Just like the setTo() method, can be a singlee-mail, a comma-delimited list or an array.

If $limit is set, “batch mode” will be enabled, which will sendthe emails to batches, with each batch not exceeding the specified$limit.

  • setSubject($subject)

Parameters:

  1. - **$subject** (_string_) E-mail subject lineReturns:

CodeIgniter\Email\Email instance (method chaining)Return type:CodeIgniter\Email\Email

Sets the email subject:

  1. $email->setSubject('This is my subject');
  • setMessage($body)

Parameters:

  1. - **$body** (_string_) E-mail message bodyReturns:

CodeIgniter\Email\Email instance (method chaining)Return type:CodeIgniter\Email\Email

Sets the e-mail message body:

  1. $email->setMessage('This is my message');
  • setAltMessage($str)

Parameters:

  1. - **$str** (_string_) Alternative e-mail message bodyReturns:

CodeIgniter\Email\Email instance (method chaining)Return type:CodeIgniter\Email\Email

Sets the alternative e-mail message body:

  1. $email->setAltMessage('This is the alternative message');

This is an optional message string which can be used if you sendHTML formatted email. It lets you specify an alternative messagewith no HTML formatting which is added to the header string forpeople who do not accept HTML email. If you do not set your ownmessage CodeIgniter will extract the message from your HTML emailand strip the tags.

  • setHeader($header, $value)

Parameters:

  1. - **$header** (_string_) Header name
  2. - **$value** (_string_) Header valueReturns:

CodeIgniter\Email\Email instance (method chaining)Return type:CodeIgniter\Email\Email

Appends additional headers to the e-mail:

  1. $email->setHeader('Header1', 'Value1');
  2. $email->setHeader('Header2', 'Value2');
  • clear($clearAttachments = false)

Parameters:

  1. - **$clearAttachments** (_bool_) Whether or not to clear attachmentsReturns:

CodeIgniter\Email\Email instance (method chaining)Return type:CodeIgniter\Email\Email

Initializes all the email variables to an empty state. This methodis intended for use if you run the email sending method in a loop,permitting the data to be reset between cycles.

  1. foreach ($list as $name => $address)
  2. {
  3. $email->clear();
  4.  
  5. $email->setTo($address);
  6. $email->setFrom('your@example.com');
  7. $email->setSubject('Here is your info '.$name);
  8. $email->setMessage('Hi ' . $name . ' Here is the info you requested.');
  9. $email->send();
  10. }

If you set the parameter to TRUE any attachments will be cleared aswell:

  1. $email->clear(true);
  • send($autoClear = true)

Parameters:

  1. - **$autoClear** (_bool_) Whether to clear message data automaticallyReturns:

TRUE on success, FALSE on failureReturn type:bool

The e-mail sending method. Returns boolean TRUE or FALSE based onsuccess or failure, enabling it to be used conditionally:

  1. if (! $email->send())
  2. {
  3. // Generate error
  4. }

This method will automatically clear all parameters if the request wassuccessful. To stop this behaviour pass FALSE:

  1. if ($email->send(false))
  2. {
  3. // Parameters won't be cleared
  4. }

Note

In order to use the printDebugger() method, you needto avoid clearing the email parameters.

Note

If BCCBatchMode is enabled, and there are more thanBCCBatchSize recipients, this method will always returnboolean TRUE.

  • attach($filename[, $disposition = ''[, $newname = null[, $mime = '']]])

Parameters:

  1. - **$filename** (_string_) File name
  2. - **$disposition** (_string_) disposition of the attachment. Mostemail clients make their own decision regardless of the MIMEspecification used here. [https://www.iana.org/assignments/cont-disp/cont-disp.xhtml](https://www.iana.org/assignments/cont-disp/cont-disp.xhtml)
  3. - **$newname** (_string_) Custom file name to use in the e-mail
  4. - **$mime** (_string_) MIME type to use (useful for buffered data)Returns:

CodeIgniter\Email\Email instance (method chaining)Return type:CodeIgniter\Email\Email

Enables you to send an attachment. Put the file path/name in the firstparameter. For multiple attachments use the method multiple times.For example:

  1. $email->attach('/path/to/photo1.jpg');
  2. $email->attach('/path/to/photo2.jpg');
  3. $email->attach('/path/to/photo3.jpg');

To use the default disposition (attachment), leave the second parameter blank,otherwise use a custom disposition:

  1. $email->attach('image.jpg', 'inline');

You can also use a URL:

  1. $email->attach('http://example.com/filename.pdf');

If you’d like to use a custom file name, you can use the third parameter:

  1. $email->attach('filename.pdf', 'attachment', 'report.pdf');

If you need to use a buffer string instead of a real - physical - file you canuse the first parameter as buffer, the third parameter as file name and the fourthparameter as mime-type:

  1. $email->attach($buffer, 'attachment', 'report.pdf', 'application/pdf');
  • setAttachmentCID($filename)

Parameters:

  1. - **$filename** (_string_) Existing attachment filenameReturns:

Attachment Content-ID or FALSE if not foundReturn type:string

Sets and returns an attachment’s Content-ID, which enables your to embed an inline(picture) attachment into HTML. First parameter must be the already attached file name.

  1. $filename = '/img/photo1.jpg';
  2. $email->attach($filename);
  3. foreach ($list as $address)
  4. {
  5. $email->setTo($address);
  6. $cid = $email->setAttachmentCID($filename);
  7. $email->setMessage('<img src="cid:'. $cid .'" alt="photo1" />');
  8. $email->send();
  9. }

Note

Content-ID for each e-mail must be re-created for it to be unique.

  • printDebugger($include = ['headers', 'subject', 'body'])

Parameters:

  1. - **$include** (_array_) Which parts of the message to print outReturns:

Formatted debug dataReturn type:string

Returns a string containing any server messages, the email headers, andthe email message. Useful for debugging.

You can optionally specify which parts of the message should be printed.Valid options are: headers, subject, body.

Example:

  1. // You need to pass FALSE while sending in order for the email data
  2. // to not be cleared - if that happens, printDebugger() would have
  3. // nothing to output.
  4. $email->send(false);
  5.  
  6. // Will only print the email headers, excluding the message subject and body
  7. $email->printDebugger(['headers']);

Note

By default, all of the raw data will be printed.