PageRenderTime 27ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/user_guide_src/source/libraries/email.rst

https://gitlab.com/atoz-chevara/CodeIgniter
ReStructuredText | 405 lines | 288 code | 117 blank | 0 comment | 0 complexity | dda662aa80c5b379d4534fc700409bdd MD5 | raw file
  1. ###########
  2. Email Class
  3. ###########
  4. CodeIgniter's robust Email Class supports the following features:
  5. - Multiple Protocols: Mail, Sendmail, and SMTP
  6. - TLS and SSL Encryption for SMTP
  7. - Multiple recipients
  8. - CC and BCCs
  9. - HTML or Plaintext email
  10. - Attachments
  11. - Word wrapping
  12. - Priorities
  13. - BCC Batch Mode, enabling large email lists to be broken into small
  14. BCC batches.
  15. - Email Debugging tools
  16. .. contents::
  17. :local:
  18. .. raw:: html
  19. <div class="custom-index container"></div>
  20. ***********************
  21. Using the Email Library
  22. ***********************
  23. Sending Email
  24. =============
  25. Sending email is not only simple, but you can configure it on the fly or
  26. set your preferences in a config file.
  27. Here is a basic example demonstrating how you might send email. Note:
  28. This example assumes you are sending the email from one of your
  29. :doc:`controllers <../general/controllers>`.
  30. ::
  31. $this->load->library('email');
  32. $this->email->from('your@example.com', 'Your Name');
  33. $this->email->to('someone@example.com');
  34. $this->email->cc('another@another-example.com');
  35. $this->email->bcc('them@their-example.com');
  36. $this->email->subject('Email Test');
  37. $this->email->message('Testing the email class.');
  38. $this->email->send();
  39. Setting Email Preferences
  40. =========================
  41. There are 21 different preferences available to tailor how your email
  42. messages are sent. You can either set them manually as described here,
  43. or automatically via preferences stored in your config file, described
  44. below:
  45. Preferences are set by passing an array of preference values to the
  46. email initialize method. Here is an example of how you might set some
  47. preferences::
  48. $config['protocol'] = 'sendmail';
  49. $config['mailpath'] = '/usr/sbin/sendmail';
  50. $config['charset'] = 'iso-8859-1';
  51. $config['wordwrap'] = TRUE;
  52. $this->email->initialize($config);
  53. .. note:: Most of the preferences have default values that will be used
  54. if you do not set them.
  55. Setting Email Preferences in a Config File
  56. ------------------------------------------
  57. If you prefer not to set preferences using the above method, you can
  58. instead put them into a config file. Simply create a new file called the
  59. email.php, add the $config array in that file. Then save the file at
  60. config/email.php and it will be used automatically. You will NOT need to
  61. use the ``$this->email->initialize()`` method if you save your
  62. preferences in a config file.
  63. Email Preferences
  64. =================
  65. The following is a list of all the preferences that can be set when
  66. sending email.
  67. =================== ====================== ============================ =======================================================================
  68. Preference Default Value Options Description
  69. =================== ====================== ============================ =======================================================================
  70. **useragent** CodeIgniter None The "user agent".
  71. **protocol** mail mail, sendmail, or smtp The mail sending protocol.
  72. **mailpath** /usr/sbin/sendmail None The server path to Sendmail.
  73. **smtp_host** No Default None SMTP Server Address.
  74. **smtp_user** No Default None SMTP Username.
  75. **smtp_pass** No Default None SMTP Password.
  76. **smtp_port** 25 None SMTP Port.
  77. **smtp_timeout** 5 None SMTP Timeout (in seconds).
  78. **smtp_keepalive** FALSE TRUE or FALSE (boolean) Enable persistent SMTP connections.
  79. **smtp_crypto** No Default tls or ssl SMTP Encryption
  80. **wordwrap** TRUE TRUE or FALSE (boolean) Enable word-wrap.
  81. **wrapchars** 76 Character count to wrap at.
  82. **mailtype** text text or html Type of mail. If you send HTML email you must send it as a complete web
  83. page. Make sure you don't have any relative links or relative image
  84. paths otherwise they will not work.
  85. **charset** ``$config['charset']`` Character set (utf-8, iso-8859-1, etc.).
  86. **validate** FALSE TRUE or FALSE (boolean) Whether to validate the email address.
  87. **priority** 3 1, 2, 3, 4, 5 Email Priority. 1 = highest. 5 = lowest. 3 = normal.
  88. **crlf** \\n "\\r\\n" or "\\n" or "\\r" Newline character. (Use "\\r\\n" to comply with RFC 822).
  89. **newline** \\n "\\r\\n" or "\\n" or "\\r" Newline character. (Use "\\r\\n" to comply with RFC 822).
  90. **bcc_batch_mode** FALSE TRUE or FALSE (boolean) Enable BCC Batch Mode.
  91. **bcc_batch_size** 200 None Number of emails in each BCC batch.
  92. **dsn** FALSE TRUE or FALSE (boolean) Enable notify message from server
  93. =================== ====================== ============================ =======================================================================
  94. Overriding Word Wrapping
  95. ========================
  96. If you have word wrapping enabled (recommended to comply with RFC 822)
  97. and you have a very long link in your email it can get wrapped too,
  98. causing it to become un-clickable by the person receiving it.
  99. CodeIgniter lets you manually override word wrapping within part of your
  100. message like this::
  101. The text of your email that
  102. gets wrapped normally.
  103. {unwrap}http://example.com/a_long_link_that_should_not_be_wrapped.html{/unwrap}
  104. More text that will be
  105. wrapped normally.
  106. Place the item you do not want word-wrapped between: {unwrap} {/unwrap}
  107. ***************
  108. Class Reference
  109. ***************
  110. .. php:class:: CI_Email
  111. .. php:method:: from($from[, $name = ''[, $return_path = NULL]])
  112. :param string $from: "From" e-mail address
  113. :param string $name: "From" display name
  114. :param string $return_path: Optional email address to redirect undelivered e-mail to
  115. :returns: CI_Email instance (method chaining)
  116. :rtype: CI_Email
  117. Sets the email address and name of the person sending the email::
  118. $this->email->from('you@example.com', 'Your Name');
  119. You can also set a Return-Path, to help redirect undelivered mail::
  120. $this->email->from('you@example.com', 'Your Name', 'returned_emails@example.com');
  121. .. note:: Return-Path can't be used if you've configured 'smtp' as
  122. your protocol.
  123. .. php:method:: reply_to($replyto[, $name = ''])
  124. :param string $replyto: E-mail address for replies
  125. :param string $name: Display name for the reply-to e-mail address
  126. :returns: CI_Email instance (method chaining)
  127. :rtype: CI_Email
  128. Sets the reply-to address. If the information is not provided the
  129. information in the :meth:from method is used. Example::
  130. $this->email->reply_to('you@example.com', 'Your Name');
  131. .. php:method:: to($to)
  132. :param mixed $to: Comma-delimited string or an array of e-mail addresses
  133. :returns: CI_Email instance (method chaining)
  134. :rtype: CI_Email
  135. Sets the email address(s) of the recipient(s). Can be a single e-mail,
  136. a comma-delimited list or an array::
  137. $this->email->to('someone@example.com');
  138. ::
  139. $this->email->to('one@example.com, two@example.com, three@example.com');
  140. ::
  141. $this->email->to(
  142. array('one@example.com', 'two@example.com', 'three@example.com')
  143. );
  144. .. php:method:: cc($cc)
  145. :param mixed $cc: Comma-delimited string or an array of e-mail addresses
  146. :returns: CI_Email instance (method chaining)
  147. :rtype: CI_Email
  148. Sets the CC email address(s). Just like the "to", can be a single e-mail,
  149. a comma-delimited list or an array.
  150. .. php:method:: bcc($bcc[, $limit = ''])
  151. :param mixed $bcc: Comma-delimited string or an array of e-mail addresses
  152. :param int $limit: Maximum number of e-mails to send per batch
  153. :returns: CI_Email instance (method chaining)
  154. :rtype: CI_Email
  155. Sets the BCC email address(s). Just like the ``to()`` method, can be a single
  156. e-mail, a comma-delimited list or an array.
  157. If ``$limit`` is set, "batch mode" will be enabled, which will send
  158. the emails to batches, with each batch not exceeding the specified
  159. ``$limit``.
  160. .. php:method:: subject($subject)
  161. :param string $subject: E-mail subject line
  162. :returns: CI_Email instance (method chaining)
  163. :rtype: CI_Email
  164. Sets the email subject::
  165. $this->email->subject('This is my subject');
  166. .. php:method:: message($body)
  167. :param string $body: E-mail message body
  168. :returns: CI_Email instance (method chaining)
  169. :rtype: CI_Email
  170. Sets the e-mail message body::
  171. $this->email->message('This is my message');
  172. .. php:method:: set_alt_message($str)
  173. :param string $str: Alternative e-mail message body
  174. :returns: CI_Email instance (method chaining)
  175. :rtype: CI_Email
  176. Sets the alternative e-mail message body::
  177. $this->email->set_alt_message('This is the alternative message');
  178. This is an optional message string which can be used if you send
  179. HTML formatted email. It lets you specify an alternative message
  180. with no HTML formatting which is added to the header string for
  181. people who do not accept HTML email. If you do not set your own
  182. message CodeIgniter will extract the message from your HTML email
  183. and strip the tags.
  184. .. php:method:: set_header($header, $value)
  185. :param string $header: Header name
  186. :param string $value: Header value
  187. :returns: CI_Email instance (method chaining)
  188. :rtype: CI_Email
  189. Appends additional headers to the e-mail::
  190. $this->email->set_header('Header1', 'Value1');
  191. $this->email->set_header('Header2', 'Value2');
  192. .. php:method:: clear([$clear_attachments = FALSE])
  193. :param bool $clear_attachments: Whether or not to clear attachments
  194. :returns: CI_Email instance (method chaining)
  195. :rtype: CI_Email
  196. Initializes all the email variables to an empty state. This method
  197. is intended for use if you run the email sending method in a loop,
  198. permitting the data to be reset between cycles.
  199. ::
  200. foreach ($list as $name => $address)
  201. {
  202. $this->email->clear();
  203. $this->email->to($address);
  204. $this->email->from('your@example.com');
  205. $this->email->subject('Here is your info '.$name);
  206. $this->email->message('Hi '.$name.' Here is the info you requested.');
  207. $this->email->send();
  208. }
  209. If you set the parameter to TRUE any attachments will be cleared as
  210. well::
  211. $this->email->clear(TRUE);
  212. .. php:method:: send([$auto_clear = TRUE])
  213. :param bool $auto_clear: Whether to clear message data automatically
  214. :returns: TRUE on success, FALSE on failure
  215. :rtype: bool
  216. The e-mail sending method. Returns boolean TRUE or FALSE based on
  217. success or failure, enabling it to be used conditionally::
  218. if ( ! $this->email->send())
  219. {
  220. // Generate error
  221. }
  222. This method will automatically clear all parameters if the request was
  223. successful. To stop this behaviour pass FALSE::
  224. if ($this->email->send(FALSE))
  225. {
  226. // Parameters won't be cleared
  227. }
  228. .. note:: In order to use the ``print_debugger()`` method, you need
  229. to avoid clearing the email parameters.
  230. .. php:method:: attach($filename[, $disposition = ''[, $newname = NULL[, $mime = '']]])
  231. :param string $filename: File name
  232. :param string $disposition: 'disposition' of the attachment. Most
  233. email clients make their own decision regardless of the MIME
  234. specification used here. https://www.iana.org/assignments/cont-disp/cont-disp.xhtml
  235. :param string $newname: Custom file name to use in the e-mail
  236. :param string $mime: MIME type to use (useful for buffered data)
  237. :returns: CI_Email instance (method chaining)
  238. :rtype: CI_Email
  239. Enables you to send an attachment. Put the file path/name in the first
  240. parameter. For multiple attachments use the method multiple times.
  241. For example::
  242. $this->email->attach('/path/to/photo1.jpg');
  243. $this->email->attach('/path/to/photo2.jpg');
  244. $this->email->attach('/path/to/photo3.jpg');
  245. To use the default disposition (attachment), leave the second parameter blank,
  246. otherwise use a custom disposition::
  247. $this->email->attach('image.jpg', 'inline');
  248. You can also use a URL::
  249. $this->email->attach('http://example.com/filename.pdf');
  250. If you'd like to use a custom file name, you can use the third paramater::
  251. $this->email->attach('filename.pdf', 'attachment', 'report.pdf');
  252. If you need to use a buffer string instead of a real - physical - file you can
  253. use the first parameter as buffer, the third parameter as file name and the fourth
  254. parameter as mime-type::
  255. $this->email->attach($buffer, 'attachment', 'report.pdf', 'application/pdf');
  256. .. php:method:: attachment_cid($filename)
  257. :param string $filename: Existing attachment filename
  258. :returns: Attachment Content-ID or FALSE if not found
  259. :rtype: string
  260. Sets and returns an attachment's Content-ID, which enables your to embed an inline
  261. (picture) attachment into HTML. First parameter must be the already attached file name.
  262. ::
  263. $filename = '/img/photo1.jpg';
  264. $this->email->attach($filename);
  265. foreach ($list as $address)
  266. {
  267. $this->email->to($address);
  268. $cid = $this->email->attachment_cid($filename);
  269. $this->email->message('<img src="cid:'. $cid .'" alt="photo1" />');
  270. $this->email->send();
  271. }
  272. .. note:: Content-ID for each e-mail must be re-created for it to be unique.
  273. .. php:method:: print_debugger([$include = array('headers', 'subject', 'body')])
  274. :param array $include: Which parts of the message to print out
  275. :returns: Formatted debug data
  276. :rtype: string
  277. Returns a string containing any server messages, the email headers, and
  278. the email messsage. Useful for debugging.
  279. You can optionally specify which parts of the message should be printed.
  280. Valid options are: **headers**, **subject**, **body**.
  281. Example::
  282. // You need to pass FALSE while sending in order for the email data
  283. // to not be cleared - if that happens, print_debugger() would have
  284. // nothing to output.
  285. $this->email->send(FALSE);
  286. // Will only print the email headers, excluding the message subject and body
  287. $this->email->print_debugger(array('headers'));
  288. .. note:: By default, all of the raw data will be printed.