diff --git a/lib/email/sender.rb b/lib/email/sender.rb index 389fc73da..9214c5975 100644 --- a/lib/email/sender.rb +++ b/lib/email/sender.rb @@ -7,6 +7,7 @@ # It also adds an HTML part for the plain text body # require_dependency 'email/renderer' +require 'uri' module Email class Sender @@ -45,6 +46,9 @@ module Email to_address: to_address, user_id: @user.try(:id)) + + @message.header['List-Id'] = Email::Sender.list_id_for(SiteSetting.title, Discourse.base_url) + add_header_to_log('X-Discourse-Reply-Key', email_log, :reply_key) add_header_to_log('X-Discourse-Post-Id', email_log, :post_id) add_header_to_log('X-Discourse-Topic-Id', email_log, :topic_id) @@ -62,6 +66,20 @@ module Email end + def self.list_id_for(site_name, base_url) + + host = "localhost" + if base_url.present? + begin + uri = URI.parse(base_url) + host = uri.host.downcase if uri.host.present? + rescue URI::InvalidURIError + end + end + + "\"#{site_name.gsub(/\"/, "'")}\" <#{Slug.for(site_name)}.#{host}>" + end + private def add_header_to_log(name, email_log, email_log_field) diff --git a/spec/components/email/sender_spec.rb b/spec/components/email/sender_spec.rb index 2bbc76496..695f4b95f 100644 --- a/spec/components/email/sender_spec.rb +++ b/spec/components/email/sender_spec.rb @@ -20,6 +20,34 @@ describe Email::Sender do Email::Sender.new(message, :hello).send end + context "list_id_for" do + + it "joins the host and forum name" do + Email::Sender.list_id_for("myforum", "http://mysite.com").should == '"myforum" ' + end + + it "uses localhost when no host is present" do + Email::Sender.list_id_for("myforum", nil).should == '"myforum" ' + end + + it "uses localhost with a weird host" do + Email::Sender.list_id_for("Fun", "this is not a real host").should == '"Fun" ' + end + + it "removes double quotes from names" do + Email::Sender.list_id_for('Quoted "Forum"', 'http://quoted.com').should == '"Quoted \'Forum\'" ' + end + + it "converts the site name to lower case and removes spaces" do + Email::Sender.list_id_for("Robin's cool Forum!", "http://robin.com").should == '"Robin\'s cool Forum!" ' + end + + it "downcases host names" do + Email::Sender.list_id_for("cool", "http://ForumSite.com").should == '"cool" ' + end + + end + context 'with a valid message' do let(:reply_key) { "abcd" * 8 } @@ -38,6 +66,11 @@ describe Email::Sender do email_sender.send end + it "adds a List-Id header to identify the forum" do + email_sender.send + message.header['List-Id'].should be_present + end + context 'email logs' do let(:email_log) { EmailLog.last }