Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 380 lines (332 sloc) 14.886 kB
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
1 require 'action_mailer/adv_attr_accessor'
2 require 'action_mailer/part'
5ddffc8 @jamis Allow for nested parts in multipart mails #1570 [Flurin Egger]
jamis authored
3 require 'action_mailer/part_container'
bde3df2 @jamis Correctly normalize newlines in outgoing emails before encoding the b…
jamis authored
4 require 'action_mailer/utils'
508c26c @jamis BCC headers are removed when sending via SMTP
jamis authored
5 require 'tmail/net'
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
6
db045db @dhh Initial
dhh authored
7 module ActionMailer #:nodoc:
8 # Usage:
9 #
10 # class ApplicationMailer < ActionMailer::Base
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
11 # # Set up properties
12 # # (Properties can also be specified via accessor methods
13 # # i.e. self.subject = "foo") and instance variables (@subject = "foo").
14 # def signup_notification(recipient)
15 # recipients recipient.email_address_with_name
16 # subject "New account information"
2789b5d @dhh Tuned documentation for release (AM)
dhh authored
17 # body { "account" => recipient }
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
18 # from "system@example.com"
19 # end
20 #
21 # # explicitly specify multipart messages
22 # def signup_notification(recipient)
23 # recipients recipient.email_address_with_name
24 # subject "New account information"
25 # from "system@example.com"
26 #
27 # part :content_type => "text/html",
28 # :body => render_message("signup-as-html", :account => recipient)
29 #
30 # part "text/plain" do |p|
31 # p.body = render_message("signup-as-plain", :account => recipient)
32 # p.transfer_encoding = "base64"
33 # end
34 # end
35 #
36 # # attachments
37 # def signup_notification(recipient)
38 # recipients recipient.email_address_with_name
39 # subject "New account information"
40 # from "system@example.com"
41 #
42 # attachment :content_type => "image/jpeg",
43 # :body => File.read("an-image.jpg")
44 #
45 # attachment "application/pdf" do |a|
46 # a.body = generate_your_pdf_here()
47 # end
db045db @dhh Initial
dhh authored
48 # end
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
49 #
50 # # implicitly multipart messages
51 # def signup_notification(recipient)
52 # recipients recipient.email_address_with_name
53 # subject "New account information"
54 # from "system@example.com"
55 # body(:account => "recipient")
56 #
57 # # ActionMailer will automatically detect and use multipart templates,
58 # # where each template is named after the name of the action, followed
59 # # by the content type. Each such detected template will be added as
60 # # a separate part to the message.
61 # #
62 # # for example, if the following templates existed:
63 # # * signup_notification.text.plain.rhtml
64 # # * signup_notification.text.html.rhtml
65 # # * signup_notification.text.xml.rxml
66 # # * signup_notification.text.x-yaml.rhtml
67 # #
68 # # Each would be rendered and added as a separate part to the message,
69 # # with the corresponding content type. The same body hash is passed to
70 # # each template.
db045db @dhh Initial
dhh authored
71 # end
72 # end
73 #
74 # # After this post_notification will look for "templates/application_mailer/post_notification.rhtml"
75 # ApplicationMailer.template_root = "templates"
76 #
77 # ApplicationMailer.create_comment_notification(david, hello_world) # => a tmail object
78 # ApplicationMailer.deliver_comment_notification(david, hello_world) # sends the email
c927aa0 @dhh Updated documentation
dhh authored
79 #
80 # = Configuration options
81 #
82 # These options are specified on the class level, like <tt>ActionMailer::Base.template_root = "/my/templates"</tt>
83 #
84 # * <tt>template_root</tt> - template root determines the base from which template references will be made.
85 #
86 # * <tt>logger</tt> - the logger is used for generating information on the mailing run if available.
87 # Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.
88 #
89 # * <tt>server_settings</tt> - Allows detailed configuration of the server:
90 # * <tt>:address</tt> Allows you to use a remote mail server. Just change it away from it's default "localhost" setting.
91 # * <tt>:port</tt> On the off change that your mail server doesn't run on port 25, you can change it.
92 # * <tt>:domain</tt> If you need to specify a HELO domain, you can do it here.
93 # * <tt>:user_name</tt> If your mail server requires authentication, set the username and password in these two settings.
94 # * <tt>:password</tt> If your mail server requires authentication, set the username and password in these two settings.
95 # * <tt>:authentication</tt> If your mail server requires authentication, you need to specify the authentication type here.
96 # This is a symbol and one of :plain, :login, :cram_md5
97 #
98 # * <tt>raise_delivery_errors</tt> - whether or not errors should be raised if the email fails to be delivered.
99 #
100 # * <tt>delivery_method</tt> - Defines a delivery method. Possible values are :smtp (default), :sendmail, and :test.
101 # Sendmail is assumed to be present at "/usr/sbin/sendmail".
102 #
103 # * <tt>perform_deliveries</tt> - Determines whether deliver_* methods are actually carried out. By default they are,
104 # but this can be turned off to help functional testing.
105 #
106 # * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful
107 # for unit and functional testing.
af56c80 @dhh Updated documentation
dhh authored
108 #
109 # * <tt>default_charset</tt> - The default charset used for the body and to encode the subject. Defaults to UTF-8. You can also
5c98152 @jamis Better multipart support with implicit multipart/alternative and sort…
jamis authored
110 # pick a different charset from inside a method with <tt>@charset</tt>.
111 # * <tt>default_content_type</tt> - The default content type used for main part of the message. Defaults to "text/plain". You
112 # can also pick a different content type from inside a method with <tt>@content_type</tt>.
113 # * <tt>default_implicit_parts_order</tt> - When a message is built implicitly (i.e. multiple parts are assemble from templates
114 # which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to
115 # ["text/html", "text/enriched", "text/plain"]. Items that appear first in the array have higher priority in the mail client
116 # and appear last in the mime encoded message. You can also pick a different order from inside a method with
117 # <tt>@implicit_parts_order</tt>.
db045db @dhh Initial
dhh authored
118 class Base
0fe8e3d @dhh Added a config example in README #1626 [courtenay]
dhh authored
119 include AdvAttrAccessor, PartContainer
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
120
c927aa0 @dhh Updated documentation
dhh authored
121 private_class_method :new #:nodoc:
db045db @dhh Initial
dhh authored
122
123 cattr_accessor :template_root
124 cattr_accessor :logger
125
126 @@server_settings = {
127 :address => "localhost",
128 :port => 25,
129 :domain => 'localhost.localdomain',
130 :user_name => nil,
131 :password => nil,
132 :authentication => nil
133 }
134 cattr_accessor :server_settings
135
136 @@raise_delivery_errors = true
137 cattr_accessor :raise_delivery_errors
138
139 @@delivery_method = :smtp
140 cattr_accessor :delivery_method
141
142 @@perform_deliveries = true
143 cattr_accessor :perform_deliveries
144
145 @@deliveries = []
146 cattr_accessor :deliveries
147
3fad0cd @dhh Added support for charsets for both subject and body. The default cha…
dhh authored
148 @@default_charset = "utf-8"
149 cattr_accessor :default_charset
150
100fd72 @jamis Added a "content_type" accessor to allow messages to explicitly speci…
jamis authored
151 @@default_content_type = "text/plain"
152 cattr_accessor :default_content_type
153
5c98152 @jamis Better multipart support with implicit multipart/alternative and sort…
jamis authored
154 @@default_implicit_parts_order = [ "text/html", "text/enriched", "text/plain" ]
155 cattr_accessor :default_implicit_parts_order
156
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
157 adv_attr_accessor :recipients, :subject, :body, :from, :sent_on, :headers,
5c98152 @jamis Better multipart support with implicit multipart/alternative and sort…
jamis authored
158 :bcc, :cc, :charset, :content_type, :implicit_parts_order,
ae1e852 @jamis Add a unified render method to ActionMailer (delegates to ActionView:…
jamis authored
159 :template, :mailer_name
165097e @dhh Added access to custom headers, like cc, bcc, and reply-to #268 [Andr…
dhh authored
160
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
161 attr_reader :mail
162
eda1719 @jamis ActionMailer::Base.deliver(email) had been accidentally removed, but …
jamis authored
163 class << self
164 def method_missing(method_symbol, *parameters)#:nodoc:
165 case method_symbol.id2name
166 when /^create_([_a-z]\w*)/ then new($1, *parameters).mail
167 when /^deliver_([_a-z]\w*)/ then new($1, *parameters).deliver!
168 when "new" then nil
169 else super
170 end
171 end
172
173 def receive(raw_email) #:nodoc:
174 logger.info "Received mail:\n #{raw_email}" unless logger.nil?
175 mail = TMail::Mail.parse(raw_email)
176 mail.base64_decode
177 new.receive(mail)
178 end
179
180 # Deliver the given mail object directly. This can be used to deliver
181 # a preconstructed mail object, like:
182 #
183 # email = MyMailer.create_some_mail(parameters)
184 # email.set_some_obscure_header "frobnicate"
185 # MyMailer.deliver(email)
186 def deliver(mail)
187 new.deliver!(mail)
188 end
189 end
190
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
191 # Instantiate a new mailer object. If +method_name+ is not +nil+, the mailer
192 # will be initialized according to the named method. If not, the mailer will
193 # remain uninitialized (useful when you only need to invoke the "receive"
194 # method, for instance).
2789b5d @dhh Tuned documentation for release (AM)
dhh authored
195 def initialize(method_name=nil, *parameters) #:nodoc:
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
196 create!(method_name, *parameters) if method_name
197 end
198
199 # Initialize the mailer via the given +method_name+. The body will be
200 # rendered and a new TMail::Mail object created.
2789b5d @dhh Tuned documentation for release (AM)
dhh authored
201 def create!(method_name, *parameters) #:nodoc:
f474f33 @jamis Move mailer initialization to a separate (overridable) method, so tha…
jamis authored
202 initialize_defaults(method_name)
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
203 send(method_name, *parameters)
204
205 # If an explicit, textual body has not been set, we check assumptions.
206 unless String === @body
207 # First, we look to see if there are any likely templates that match,
208 # which include the content-type in their file name (i.e.,
209 # "the_template_file.text.html.rhtml", etc.).
210 if @parts.empty?
813a8b9 @jamis Allow template to be explicitly specified #1448 [tuxie@dekadance.se]
jamis authored
211 templates = Dir.glob("#{template_path}/#{@template}.*")
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
212 templates.each do |path|
213 type = (File.basename(path).split(".")[1..-2] || []).join("/")
214 next if type.empty?
215 @parts << Part.new(:content_type => type,
053cb22 @jamis Use the real charset for parts generated by a template, instead of th…
jamis authored
216 :disposition => "inline", :charset => charset,
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
217 :body => render_message(File.basename(path).split(".")[0..-2].join('.'), @body))
218 end
5c98152 @jamis Better multipart support with implicit multipart/alternative and sort…
jamis authored
219 unless @parts.empty?
220 @content_type = "multipart/alternative"
221 @parts = sort_parts(@parts, @implicit_parts_order)
222 end
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
223 end
db045db @dhh Initial
dhh authored
224
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
225 # Then, if there were such templates, we check to see if we ought to
226 # also render a "normal" template (without the content type). If a
227 # normal template exists (or if there were no implicit parts) we render
228 # it.
229 template_exists = @parts.empty?
813a8b9 @jamis Allow template to be explicitly specified #1448 [tuxie@dekadance.se]
jamis authored
230 template_exists ||= Dir.glob("#{template_path}/#{@template}.*").any? { |i| i.split(".").length == 2 }
231 @body = render_message(@template, @body) if template_exists
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
232
233 # Finally, if there are other message parts and a textual body exists,
234 # we shift it onto the front of the parts and set the body to nil (so
235 # that create_mail doesn't try to render it in addition to the parts).
236 if !@parts.empty? && String === @body
237 @parts.unshift Part.new(:charset => charset, :body => @body)
238 @body = nil
425aa50 @dhh Added receiver method for incoming email
dhh authored
239 end
db045db @dhh Initial
dhh authored
240 end
241
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
242 # build the mail object itself
243 @mail = create_mail
244 end
db045db @dhh Initial
dhh authored
245
eda1719 @jamis ActionMailer::Base.deliver(email) had been accidentally removed, but …
jamis authored
246 # Delivers a TMail::Mail object. By default, it delivers the cached mail
247 # object (from the #create! method). If no cached mail object exists, and
248 # no alternate has been given as the parameter, this will fail.
249 def deliver!(mail = @mail) #:nodoc:
250 raise "no mail object available for delivery!" unless mail
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
251 logger.info "Sent mail:\n #{mail.encoded}" unless logger.nil?
256e800 @dhh Fixed quoting for all address headers, not just to #955 [Jamis Buck] …
dhh authored
252
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
253 begin
eda1719 @jamis ActionMailer::Base.deliver(email) had been accidentally removed, but …
jamis authored
254 send("perform_delivery_#{delivery_method}", mail) if perform_deliveries
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
255 rescue Object => e
256 raise e if raise_delivery_errors
257 end
3fad0cd @dhh Added support for charsets for both subject and body. The default cha…
dhh authored
258
eda1719 @jamis ActionMailer::Base.deliver(email) had been accidentally removed, but …
jamis authored
259 return mail
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
260 end
3fad0cd @dhh Added support for charsets for both subject and body. The default cha…
dhh authored
261
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
262 private
f474f33 @jamis Move mailer initialization to a separate (overridable) method, so tha…
jamis authored
263 # Set up the default values for the various instance variables of this
264 # mailer. Subclasses may override this method to provide different
265 # defaults.
266 def initialize_defaults(method_name)
267 @bcc = @cc = @from = @recipients = @sent_on = @subject = nil
268 @charset = @@default_charset.dup
269 @content_type = @@default_content_type.dup
270 @implicit_parts_order = @@default_implicit_parts_order.dup
271 @template = method_name
ae1e852 @jamis Add a unified render method to ActionMailer (delegates to ActionView:…
jamis authored
272 @mailer_name = Inflector.underscore(self.class.name)
f474f33 @jamis Move mailer initialization to a separate (overridable) method, so tha…
jamis authored
273 @parts = []
274 @headers = {}
275 @body = {}
276 end
277
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
278 def render_message(method_name, body)
ae1e852 @jamis Add a unified render method to ActionMailer (delegates to ActionView:…
jamis authored
279 render :file => method_name, :body => body
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
280 end
ae1e852 @jamis Add a unified render method to ActionMailer (delegates to ActionView:…
jamis authored
281
282 def render(opts)
283 body = opts.delete(:body)
284 initialize_template_class(body).render(opts)
285 end
286
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
287 def template_path
ae1e852 @jamis Add a unified render method to ActionMailer (delegates to ActionView:…
jamis authored
288 "#{template_root}/#{mailer_name}"
db045db @dhh Initial
dhh authored
289 end
290
5ec990a @jamis Helper support for ActionMailer
jamis authored
291 def initialize_template_class(assigns)
292 ActionView::Base.new(template_path, assigns, self)
293 end
294
5c98152 @jamis Better multipart support with implicit multipart/alternative and sort…
jamis authored
295 def sort_parts(parts, order = [])
296 order = order.collect { |s| s.downcase }
297
298 parts = parts.sort do |a, b|
299 a_ct = a.content_type.downcase
300 b_ct = b.content_type.downcase
301
302 a_in = order.include? a_ct
303 b_in = order.include? b_ct
304
305 s = case
306 when a_in && b_in
307 order.index(a_ct) <=> order.index(b_ct)
308 when a_in
309 -1
310 when b_in
311 1
312 else
313 a_ct <=> b_ct
314 end
315
316 # reverse the ordering because parts that come last are displayed
317 # first in mail clients
318 (s * -1)
319 end
320
321 parts
322 end
323
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
324 def create_mail
325 m = TMail::Mail.new
74a612c @dhh Added that delivery errors are caught in a way so the mail is still r…
dhh authored
326
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
327 m.subject, = quote_any_if_necessary(charset, subject)
328 m.to, m.from = quote_any_address_if_necessary(charset, recipients, from)
329 m.bcc = quote_address_if_necessary(bcc, charset) unless bcc.nil?
330 m.cc = quote_address_if_necessary(cc, charset) unless cc.nil?
74a612c @dhh Added that delivery errors are caught in a way so the mail is still r…
dhh authored
331
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
332 m.date = sent_on.to_time rescue sent_on if sent_on
333 headers.each { |k, v| m[k] = v }
db045db @dhh Initial
dhh authored
334
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
335 if @parts.empty?
100fd72 @jamis Added a "content_type" accessor to allow messages to explicitly speci…
jamis authored
336 m.set_content_type content_type, nil, { "charset" => charset }
bde3df2 @jamis Correctly normalize newlines in outgoing emails before encoding the b…
jamis authored
337 m.body = Utils.normalize_new_lines(body)
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
338 else
339 if String === body
340 part = TMail::Mail.new
bde3df2 @jamis Correctly normalize newlines in outgoing emails before encoding the b…
jamis authored
341 part.body = Utils.normalize_new_lines(body)
100fd72 @jamis Added a "content_type" accessor to allow messages to explicitly speci…
jamis authored
342 part.set_content_type content_type, nil, { "charset" => charset }
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
343 part.set_content_disposition "inline"
344 m.parts << part
345 end
3fad0cd @dhh Added support for charsets for both subject and body. The default cha…
dhh authored
346
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
347 @parts.each do |p|
348 part = (TMail::Mail === p ? p : p.to_mail(self))
349 m.parts << part
350 end
3b4eb7a @jamis Allow specific "multipart/xxx" content-type to be set on multipart me…
jamis authored
351
352 m.set_content_type(content_type, nil, { "charset" => charset }) if content_type =~ /multipart/
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
353 end
256e800 @dhh Fixed quoting for all address headers, not just to #955 [Jamis Buck] …
dhh authored
354
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
355 @mail = m
256e800 @dhh Fixed quoting for all address headers, not just to #955 [Jamis Buck] …
dhh authored
356 end
357
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
358 def perform_delivery_smtp(mail)
508c26c @jamis BCC headers are removed when sending via SMTP
jamis authored
359 destinations = mail.destinations
360 mail.ready_to_send
361
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
362 Net::SMTP.start(server_settings[:address], server_settings[:port], server_settings[:domain],
363 server_settings[:user_name], server_settings[:password], server_settings[:authentication]) do |smtp|
508c26c @jamis BCC headers are removed when sending via SMTP
jamis authored
364 smtp.sendmail(mail.encoded, mail.from, destinations)
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
365 end
256e800 @dhh Fixed quoting for all address headers, not just to #955 [Jamis Buck] …
dhh authored
366 end
367
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
368 def perform_delivery_sendmail(mail)
369 IO.popen("/usr/sbin/sendmail -i -t","w+") do |sm|
bb62568 @dhh Fix problem with sendmail delivery where headers should be delimited …
dhh authored
370 sm.print(mail.encoded.gsub(/\r/, ''))
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
371 sm.flush
256e800 @dhh Fixed quoting for all address headers, not just to #955 [Jamis Buck] …
dhh authored
372 end
373 end
374
359caef @jamis A very thorough refactoring, resulting in new mail property setters a…
jamis authored
375 def perform_delivery_test(mail)
376 deliveries << mail
377 end
db045db @dhh Initial
dhh authored
378 end
379 end
Something went wrong with that request. Please try again.