Class: Email::Receiver

Inherits:
Object
  • Object
show all
Defined in:
lib/email/receiver.rb

Defined Under Namespace

Classes: AutoGeneratedEmailError, BadDestinationAddress, BouncedEmailError, EmailNotAllowed, EmptyEmailError, FromReplyByAddressError, InactiveUserError, InsufficientTrustLevelError, InvalidPost, InvalidPostAction, NoBodyDetectedError, NoSenderDetectedError, OldDestinationError, ProcessingError, ReplyNotAllowedError, ReplyToDigestError, ReplyUserNotMatchingError, ScreenedEmailError, SilencedUserError, StrangersNotAllowedError, TooManyRecipientsError, TooShortPost, TopicClosedError, TopicNotFoundError, UnsubscribeNotAllowed, UserNotFoundError

Constant Summary collapse

COMMON_ENCODINGS =
[-"utf-8", -"windows-1252", -"iso-8859-1"]
HTML_EXTRACTERS =
[
  [:gmail, /class="gmail_(signature|extra)/],
  [:outlook, /id="(divRplyFwdMsg|Signature)"/],
  [:word, /class="WordSection1"/],
  [:exchange, /name="message(Body|Reply)Section"/],
  [:apple_mail, /id="AppleMailSignature"/],
  [:mozilla, /class="moz-/],
  [:protonmail, /class="protonmail_/],
  [:zimbra, /data-marker="__/],
  [:newton, /(id|class)="cm_/],
  [:front, /class="front-/],
]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mail_string, opts = {}) ⇒ Receiver

Returns a new instance of Receiver.

Raises:



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/email/receiver.rb', line 104

def initialize(mail_string, opts = {})
  raise EmptyEmailError if mail_string.blank?
  @staged_users = []
  @created_staged_users = []
  @raw_email = mail_string

  COMMON_ENCODINGS.each do |encoding|
    fixed = try_to_encode(mail_string, encoding)
    break @raw_email = fixed if fixed.present?
  end

  @mail = Mail.new(@raw_email)
  @message_id = @mail.message_id.presence || Digest::MD5.hexdigest(mail_string)
  @opts = opts
  @destinations ||= opts[:destinations]
end

Instance Attribute Details

#incoming_emailObject (readonly)

Returns the value of attribute incoming_email.



93
94
95
# File 'lib/email/receiver.rb', line 93

def incoming_email
  @incoming_email
end

#mailObject (readonly)

Returns the value of attribute mail.



95
96
97
# File 'lib/email/receiver.rb', line 95

def mail
  @mail
end

#message_idObject (readonly)

Returns the value of attribute message_id.



96
97
98
# File 'lib/email/receiver.rb', line 96

def message_id
  @message_id
end

#raw_emailObject (readonly)

Returns the value of attribute raw_email.



94
95
96
# File 'lib/email/receiver.rb', line 94

def raw_email
  @raw_email
end

Class Method Details

.check_address(address, include_verp = false) ⇒ Object



850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
# File 'lib/email/receiver.rb', line 850

def self.check_address(address, include_verp = false)
  # only check for a group/category when 'email_in' is enabled
  if SiteSetting.email_in
    group = Group.find_by_email(address)
    return group if group

    category = Category.find_by_email(address)
    return category if category
  end

  # reply
  match = Email::Receiver.reply_by_email_address_regex(true, include_verp).match(address)
  if match && match.captures
    match.captures.each do |c|
      next if c.blank?
      post_reply_key = PostReplyKey.find_by(reply_key: c)
      return post_reply_key if post_reply_key
    end
  end
  nil
end

.elided_html(elided) ⇒ Object



1568
1569
1570
1571
1572
1573
1574
1575
# File 'lib/email/receiver.rb', line 1568

def self.elided_html(elided)
  html = +"\n\n" << "<details class='elided'>" << "\n"
  html << "<summary title='#{I18n.t("emails.incoming.show_trimmed_content")}'>&#183;&#183;&#183;</summary>" <<
    "\n\n"
  html << elided << "\n\n"
  html << "</details>" << "\n"
  html
end

.extract_email_address_and_name(value) ⇒ Object



759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
# File 'lib/email/receiver.rb', line 759

def self.extract_email_address_and_name(value)
  begin
    # ensure the email header value is a string
    value = value.to_s
    # in embedded emails, converts [mailto:[email protected]] to <[email protected]>
    value = value.gsub(/\[mailto:([^\[\]]+?)\]/, "<\\1>")
    # 'mailto:' suffix isn't supported by Mail::Address parsing
    value = value.gsub("mailto:", "")
    # parse the email header value
    parsed = Mail::Address.new(value)
    # extract the email address and name
    mail = parsed.address.to_s.downcase.strip
    name = parsed.name.to_s.strip
    # ensure the email address is "valid"
    if mail.include?("@")
      # remove surrounding quotes from the name
      name = name[1...-1] if name.size > 2 && name[/\A(['"]).+(\1)\z/]
      # return the email address and name
      [mail, name]
    end
  rescue Mail::Field::ParseError, Mail::Field::IncompleteParseError
    # something went wrong parsing the email header value, return nil
  end
end

.extract_email_address_and_name_from_mailman(mail) ⇒ Object



740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
# File 'lib/email/receiver.rb', line 740

def self.extract_email_address_and_name_from_mailman(mail)
  list_address, _ = Email::Receiver.extract_email_address_and_name(mail[:list_post])
  list_address, _ =
    Email::Receiver.extract_email_address_and_name(mail[:x_beenthere]) if list_address.blank?

  return if list_address.blank?

  # the CC header often includes the name of the sender
  address_to_name = mail[:cc]&.element&.addresses&.to_h { [_1.address, _1.name] } || {}

  %i[from reply_to x_mailfrom x_original_from].each do |header|
    next if mail[header].blank?
    email, name = Email::Receiver.extract_email_address_and_name(mail[header])
    if email.present? && email != list_address
      return email, name.presence || address_to_name[email]
    end
  end
end

.extract_references(references) ⇒ Object



1261
1262
1263
1264
1265
1266
1267
# File 'lib/email/receiver.rb', line 1261

def self.extract_references(references)
  if Array === references
    references
  elsif references.present?
    references.split(/[\s,]/).map { |r| Email::MessageIdService.message_id_clean(r) }
  end
end

.extract_reply_message_ids(mail, max_message_id_count:) ⇒ Object



1253
1254
1255
1256
1257
1258
1259
# File 'lib/email/receiver.rb', line 1253

def self.extract_reply_message_ids(mail, max_message_id_count:)
  message_ids = [mail.in_reply_to, Email::Receiver.extract_references(mail.references)]
  message_ids.flatten!
  message_ids.select!(&:present?)
  message_ids.uniq!
  message_ids.first(max_message_id_count)
end

.formatsObject



100
101
102
# File 'lib/email/receiver.rb', line 100

def self.formats
  @formats ||= Enum.new(plaintext: 1, markdown: 2)
end

.reply_by_email_address_regex(extract_reply_key = true, include_verp = false) ⇒ Object



1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
# File 'lib/email/receiver.rb', line 1199

def self.reply_by_email_address_regex(extract_reply_key = true, include_verp = false)
  reply_addresses = [SiteSetting.reply_by_email_address]
  reply_addresses << (SiteSetting.alternative_reply_by_email_addresses.presence || "").split(
    "|",
  )

  if include_verp && SiteSetting.reply_by_email_address.present? &&
       SiteSetting.reply_by_email_address["+"]
    reply_addresses << SiteSetting.reply_by_email_address.sub(
      "%{reply_key}",
      "verp-%{reply_key}",
    )
  end

  reply_addresses.flatten!
  reply_addresses.select!(&:present?)
  reply_addresses.map! { |a| Regexp.escape(a) }
  reply_addresses.map! { |a| a.gsub("\+", "\+?") }
  reply_addresses.map! { |a| a.gsub(Regexp.escape("%{reply_key}"), "(\\h{32})?") }
  if reply_addresses.empty?
    /$a/ # a regex that can never match
  else
    /#{reply_addresses.join("|")}/
  end
end

.update_bounce_score(email, score) ⇒ Object



376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# File 'lib/email/receiver.rb', line 376

def self.update_bounce_score(email, score)
  if user = User.find_by_email(email)
    old_bounce_score = user.user_stat.bounce_score
    new_bounce_score = old_bounce_score + score
    range = (old_bounce_score + 1..new_bounce_score)

    user.user_stat.bounce_score = new_bounce_score
    user.user_stat.reset_bounce_score_after =
      SiteSetting.reset_bounce_score_after_days.days.from_now
    user.user_stat.save!

    if range === SiteSetting.bounce_score_threshold
      # NOTE: we check bounce_score before sending emails
      # So log we revoked the email...
      reason =
        I18n.t(
          "user.email.revoked",
          email: user.email,
          date: user.user_stat.reset_bounce_score_after,
        )
      StaffActionLogger.new(Discourse.system_user).log_revoke_email(user, reason)
      # ... and PM the user
      SystemMessage.create_from_system_user(user, :email_revoked)
    end
  end
end

Instance Method Details

#add_attachments(raw, user, options = {}) ⇒ Object



1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
# File 'lib/email/receiver.rb', line 1367

def add_attachments(raw, user, options = {})
  raw = raw.dup

  upload_ids =
    UploadReference.where(
      target_id: Post.where(topic_id: options[:topic_id]).select(:id),
    ).pluck("DISTINCT upload_id")

  upload_shas = Upload.where(id: upload_ids).pluck("DISTINCT COALESCE(original_sha1, sha1)")

  is_duplicate = ->(upload_id, upload_sha, attachment) do
    return true if upload_id && upload_ids.include?(upload_id)
    return true if upload_sha && upload_shas.include?(upload_sha)

    if attachment.respond_to?(:url) && attachment.url&.start_with?("cid:") &&
         attachment.content_type&.start_with?("image/")
      return true if @cids&.include?(attachment.url)
    end

    false
  end

  added_attachments = []
  rejected_attachments = []

  attachments.each do |attachment|
    tmp = Tempfile.new(["discourse-email-attachment", File.extname(attachment.filename)])
    begin
      # read attachment
      File.open(tmp.path, "w+b") { |f| f.write attachment.body.decoded }
      # create the upload for the user
      opts = { for_group_message: options[:is_group_message] }
      upload = UploadCreator.new(tmp, attachment.filename, opts).create_for(user.id)
      upload_sha = upload.original_sha1.presence || upload.sha1
      if upload.errors.empty?
        # try to inline images
        if attachment.content_type&.start_with?("image/")
          if raw[attachment.url]
            raw.sub!(attachment.url, upload.url)

            InlineUploads.match_img(
              raw,
              uploads: {
                upload.url => upload,
              },
            ) do |match, src, replacement, _|
              raw = raw.sub(match, replacement) if src == upload.url
            end
          elsif raw[/\[image:[^\]]*\]/i]
            raw.sub!(/\[image:[^\]]*\]/i, UploadMarkdown.new(upload).to_markdown)
          elsif !is_duplicate[upload.id, upload_sha, attachment]
            added_attachments << upload
          end
        elsif !is_duplicate[upload.id, upload_sha, attachment]
          added_attachments << upload
        end
      else
        rejected_attachments << upload
        raw << "\n\n#{I18n.t("emails.incoming.missing_attachment", filename: upload.original_filename)}\n\n"
      end
    ensure
      tmp&.close!
    end
  end

  if rejected_attachments.present? && !user.staged?
    notify_about_rejected_attachment(rejected_attachments)
  end

  if added_attachments.present?
    markdown =
      added_attachments.map { |upload| UploadMarkdown.new(upload).to_markdown }.join("\n")
    if markdown.present?
      raw << "\n\n"
      raw << "[details=\"#{I18n.t("emails.incoming.attachments")}\"]"
      raw << "\n\n"
      raw << markdown
      raw << "\n\n"
      raw << "[/details]"
    end
  end

  raw
end

#add_elided_to_raw!(options) ⇒ Object



1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
# File 'lib/email/receiver.rb', line 1473

def add_elided_to_raw!(options)
  is_private_message =
    options[:archetype] == Archetype.private_message || options[:topic].try(:private_message?)

  # only add elided part in messages
  if options[:elided].present? &&
       (SiteSetting.always_show_trimmed_content || is_private_message)
    options[:raw] << Email::Receiver.elided_html(options[:elided])
    options[:elided] = ""
  end
end

#add_other_addresses(post, sender, mail_object) ⇒ Object



1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
# File 'lib/email/receiver.rb', line 1577

def add_other_addresses(post, sender, mail_object)
  max_staged_users_post = nil

  %i[to cc bcc].each do |d|
    next if mail_object[d].blank?

    mail_object[d].each do |address_field|
      begin
        address_field.decoded
        email = address_field.address.downcase
        display_name = address_field.display_name.try(:to_s)
        next if !email.include?("@")

        if should_invite?(email)
          user = User.find_by_email(email)

          # cap number of staged users created per email
          if (!user || user.staged) &&
               @staged_users.count >= SiteSetting.maximum_staged_users_per_email
            max_staged_users_post ||=
              post.topic.add_moderator_post(
                sender,
                I18n.t("emails.incoming.maximum_staged_user_per_email_reached"),
                import_mode: @opts[:import_mode],
              )
            next
          end

          user = find_or_create_user(email, display_name, user: user)
          if user && can_invite?(post.topic, user)
            post.topic.topic_allowed_users.create!(user_id: user.id)
            TopicUser.auto_notification_for_staging(
              user.id,
              post.topic_id,
              TopicUser.notification_reasons[:auto_watch],
            )
            post.topic.add_small_action(
              sender,
              "invited_user",
              user.username,
              import_mode: @opts[:import_mode],
            )
          end
        end
      rescue ActiveRecord::RecordInvalid, EmailNotAllowed
        # don't care if user already allowed or the user's email address is not allowed
      end
    end
  end
end

#all_destinationsObject



826
827
828
829
830
831
832
# File 'lib/email/receiver.rb', line 826

def all_destinations
  @all_destinations ||= [
    @mail.destinations,
    [@mail[:x_forwarded_to]].flatten.compact.map(&:decoded),
    [@mail[:delivered_to]].flatten.compact.map(&:decoded),
  ].flatten.select(&:present?).uniq.lazy
end

#attachmentsObject



1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
# File 'lib/email/receiver.rb', line 1348

def attachments
  @attachments ||=
    begin
      attachments = @mail.attachments.select { |attachment| is_allowed?(attachment) }
      attachments << @mail if @mail.attachment? && is_allowed?(@mail)

      @mail.parts.each { |part| attachments << part if part.attachment? && is_allowed?(part) }

      attachments.uniq!
      attachments
    end
end

#auth_res_actionObject



428
429
430
# File 'lib/email/receiver.rb', line 428

def auth_res_action
  @auth_res_action ||= AuthenticationResults.new(@mail.header[:authentication_results]).action
end

#bounce_keyObject



363
364
365
366
367
368
369
# File 'lib/email/receiver.rb', line 363

def bounce_key
  @bounce_key ||=
    begin
      verp = all_destinations.select { |to| to[/\+verp-\h{32}@/] }.first
      verp && verp[/\+verp-(\h{32})@/, 1]
    end
end

#can_invite?(topic, user) ⇒ Boolean

Returns:

  • (Boolean)


1633
1634
1635
1636
1637
1638
1639
# File 'lib/email/receiver.rb', line 1633

def can_invite?(topic, user)
  !topic.topic_allowed_users.where(user_id: user.id).exists? &&
    !topic
      .topic_allowed_groups
      .where("group_id IN (SELECT group_id FROM group_users WHERE user_id = ?)", user.id)
      .exists?
end

#category_email_in_regexObject



1234
1235
1236
1237
1238
1239
1240
1241
1242
# File 'lib/email/receiver.rb', line 1234

def category_email_in_regex
  @category_email_in_regex ||=
    Regexp.union Category
                   .pluck(:email_in)
                   .select(&:present?)
                   .map { |e| e.split("|") }
                   .flatten
                   .uniq
end

#contains_email_address_of_user?(addresses, user) ⇒ Boolean

Returns:

  • (Boolean)


1026
1027
1028
1029
1030
1031
# File 'lib/email/receiver.rb', line 1026

def contains_email_address_of_user?(addresses, user)
  return false if addresses.blank?

  addresses = addresses.split(";")
  user.user_emails.any? { |user_email| addresses.include?(user_email.email) }
end

#contains_reply_by_email_address(addresses, reply_key) ⇒ Object



1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
# File 'lib/email/receiver.rb', line 1033

def contains_reply_by_email_address(addresses, reply_key)
  return false if addresses.blank?

  addresses
    .split(";")
    .each do |address|
      match = Email::Receiver.reply_by_email_address_regex.match(address)
      return true if match && match.captures&.include?(reply_key)
    end

  false
end

#create_group_post(group, user, body, elided) ⇒ Object



927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
# File 'lib/email/receiver.rb', line 927

def create_group_post(group, user, body, elided)
  message_ids = Email::Receiver.extract_reply_message_ids(@mail, max_message_id_count: 5)

  # Incoming emails with matching message ids, and then cross references
  # these with any email addresses for the user vs to/from/cc of the
  # incoming emails. in effect, any incoming email record for these
  # message ids where the user is involved in any way will be returned.
  incoming_emails = IncomingEmail.where(message_id: message_ids)
  if !group.allow_unknown_sender_topic_replies
    incoming_emails = incoming_emails.addressed_to_user(user)
  end
  post_ids = incoming_emails.pluck(:post_id) || []

  # If the user is directly replying to an email send to them from discourse,
  # there will be a corresponding EmailLog record, so we can use that as the
  # reply post if it exists.
  #
  # Since In-Reply-To can technically have multiple message ids, we only
  # consider the first one here to simplify things.
  first_in_reply_to = Array.wrap(mail.in_reply_to).first
  if Email::MessageIdService.discourse_generated_message_id?(first_in_reply_to)
    post_id_from_email_log =
      EmailLog
        .where(message_id: first_in_reply_to)
        .addressed_to_user(user)
        .order(created_at: :desc)
        .limit(1)
        .pluck(:post_id)
        .last
    post_ids << post_id_from_email_log if post_id_from_email_log
  end

  target_post = post_ids.any? && Post.where(id: post_ids).order(:created_at).last
  too_old_for_group_smtp = (destination_too_old?(target_post) && group.smtp_enabled)

  if target_post.blank? || too_old_for_group_smtp
    create_topic(
      user: user,
      raw: new_group_topic_body(body, target_post, too_old_for_group_smtp),
      elided: elided,
      title: subject,
      archetype: Archetype.private_message,
      target_group_names: [group.name],
      is_group_message: true,
      skip_validations: true,
    )
  else
    # This must be done for the unknown user (who is staged) to
    # be allowed to post a reply in the topic.
    if group.allow_unknown_sender_topic_replies
      target_post.topic.topic_allowed_users.find_or_create_by!(user_id: user.id)
    end

    create_reply(
      user: user,
      raw: body,
      elided: elided,
      post: target_post,
      topic: target_post.topic,
      skip_validations: true,
    )
  end
end

#create_incoming_emailObject



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/email/receiver.rb', line 183

def create_incoming_email
  cc_addresses = Array.wrap(@mail.cc)
  cc_addresses.concat(embedded_email.cc) if has_been_forwarded? && embedded_email&.cc
  IncomingEmail.create(
    message_id: @message_id,
    raw: Email::Cleaner.new(@raw_email).execute,
    subject: subject,
    from_address: @from_email,
    to_addresses: @mail.to,
    cc_addresses: cc_addresses,
    imap_uid_validity: @opts[:imap_uid_validity],
    imap_uid: @opts[:imap_uid],
    imap_group_id: @opts[:imap_group_id],
    imap_sync: false,
    created_via: IncomingEmail.created_via_types[@opts[:source] || :unknown],
  )
end

#create_post(options = {}) ⇒ Object

Raises:



1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
# File 'lib/email/receiver.rb', line 1485

def create_post(options = {})
  options[:import_mode] = @opts[:import_mode]

  options[:via_email] = true
  options[:raw_email] = @raw_email

  options[:created_at] ||= @mail.date
  options[:created_at] = DateTime.now if options[:created_at] > DateTime.now

  add_elided_to_raw!(options)

  if sent_to_mailinglist_mirror?
    options[:skip_validations] = true
    options[:skip_guardian] = true
  else
    options[:email_spam] = is_spam?
    options[:first_post_checks] = true if is_spam?
    options[:email_auth_res_action] = auth_res_action
  end

  user = options.delete(:user)

  if options[:bounce]
    options[:raw] = I18n.t(
      "system_messages.email_bounced",
      email: user.email,
      raw: options[:raw],
    )
    user = Discourse.system_user
    options[:post_type] = Post.types[:whisper]
  end

  # To avoid race conditions with the post alerter and Group SMTP
  # emails, we skip the jobs here and enqueue them only _after_
  # the incoming email has been updated with the post and topic.
  options[:skip_jobs] = true
  options[:skip_events] = true
  result = NewPostManager.new(user, options).perform

  errors = result.errors.full_messages
  if errors.any? { |message|
       message.include?(I18n.t("activerecord.attributes.post.raw").strip) &&
         message.include?(
           I18n.t("errors.messages.too_short", count: SiteSetting.min_post_length).strip,
         )
     }
    raise TooShortPost
  end

  raise InvalidPost, errors.join("\n") if result.errors.present?

  if result.post
    IncomingEmail.transaction do
      @incoming_email.update_columns(topic_id: result.post.topic_id, post_id: result.post.id)
      result.post.update(outbound_message_id: @incoming_email.message_id)
    end

    if result.post.topic&.private_message? && !is_bounce?
      add_other_addresses(result.post, user, @mail)

      if has_been_forwarded?
        add_other_addresses(result.post, @forwarded_by_user || user, embedded_email)
      end
    end

    # Alert the people involved in the topic now that the incoming email
    # has been linked to the post.
    PostJobsEnqueuer.new(
      result.post,
      result.post.topic,
      options[:topic_id].blank?,
      import_mode: options[:import_mode],
      post_alert_options: options[:post_alert_options],
    ).enqueue_jobs
    if result.post.is_first_post?
      DiscourseEvent.trigger(:topic_created, result.post.topic, options, user)
    end
    DiscourseEvent.trigger(:post_created, result.post, options, user)
  end

  result.post
end

#create_post_action(user, post, type) ⇒ Object

Raises:



1338
1339
1340
1341
# File 'lib/email/receiver.rb', line 1338

def create_post_action(user, post, type)
  result = PostActionCreator.new(user, post, type).perform
  raise InvalidPostAction.new if result.failed? && result.forbidden
end

#create_post_with_attachments(options = {}) ⇒ Object



1361
1362
1363
1364
1365
# File 'lib/email/receiver.rb', line 1361

def create_post_with_attachments(options = {})
  add_elided_to_raw!(options)
  options[:raw] = add_attachments(options[:raw], options[:user], options)
  create_post(options)
end

#create_reply(options = {}) ⇒ Object

Raises:



1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
# File 'lib/email/receiver.rb', line 1309

def create_reply(options = {})
  raise TopicNotFoundError if options[:topic].nil? || options[:topic].trashed?
  if options[:bounce] && options[:topic].archetype != Archetype.private_message
    raise BouncedEmailError
  end

  options[:post] = nil if options[:post]&.trashed?
  if options[:topic].archetype == Archetype.private_message
    enable_email_pm_setting(options[:user])
  end

  if post_action_type = post_action_for(options[:raw])
    create_post_action(options[:user], options[:post], post_action_type)
  elsif notification_level = notification_level_for(options[:raw])
    TopicUser.change(
      options[:user].id,
      options[:post].topic_id,
      notification_level: notification_level,
    )
  else
    raise TopicClosedError if options[:topic].closed?
    options[:topic_id] = options[:topic].id
    options[:reply_to_post_number] = options[:post]&.post_number
    options[:is_group_message] = options[:topic].private_message? &&
      options[:topic].allowed_groups.exists?
    create_post_with_attachments(options)
  end
end

#create_topic(options = {}) ⇒ Object



1286
1287
1288
1289
1290
# File 'lib/email/receiver.rb', line 1286

def create_topic(options = {})
  enable_email_pm_setting(options[:user]) if options[:archetype] == Archetype.private_message

  create_post_with_attachments(options)
end

#delete_created_staged_usersObject



1654
1655
1656
1657
1658
1659
1660
# File 'lib/email/receiver.rb', line 1654

def delete_created_staged_users
  @created_staged_users.each do |user|
    @incoming_email.update_columns(user_id: nil) if @incoming_email.user&.id == user.id

    UserDestroyer.new(Discourse.system_user).destroy(user, quiet: true) if user.posts.count == 0
  end
end

#destination_too_old?(post) ⇒ Boolean

Returns:

  • (Boolean)


1670
1671
1672
1673
1674
# File 'lib/email/receiver.rb', line 1670

def destination_too_old?(post)
  return false if post.blank?
  num_of_days = SiteSetting.disallow_reply_by_email_after_days
  num_of_days > 0 && post.created_at < num_of_days.days.ago
end

#destinationsObject



834
835
836
837
# File 'lib/email/receiver.rb', line 834

def destinations
  @destinations ||=
    all_destinations.map { |d| Email::Receiver.check_address(d, is_bounce?) }.reject(&:blank?)
end

#email_logObject



371
372
373
374
# File 'lib/email/receiver.rb', line 371

def email_log
  return nil if bounce_key.blank?
  @email_log ||= EmailLog.find_by(bounce_key: bounce_key)
end

#embedded_emailObject



1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
# File 'lib/email/receiver.rb', line 1057

def embedded_email
  @embedded_email ||=
    if embedded_email_raw.present?
      mail = Mail.new(embedded_email_raw)
      Email::Validator.ensure_valid_address_lists!(mail)
      mail
    else
      nil
    end
end

#embedded_email_rawObject



1050
1051
1052
1053
1054
1055
# File 'lib/email/receiver.rb', line 1050

def embedded_email_raw
  return @embedded_email_raw if @embedded_email_raw
  text = fix_charset(@mail.multipart? ? @mail.text_part : @mail)
  @embedded_email_raw, @before_embedded = EmailReplyTrimmer.extract_embedded_email(text)
  @embedded_email_raw
end

#enable_email_pm_setting(user) ⇒ Object



1662
1663
1664
1665
1666
1667
1668
# File 'lib/email/receiver.rb', line 1662

def enable_email_pm_setting(user)
  # ensure user PM emails are enabled (since user is posting via email)
  if !user.staged &&
       user.user_option.email_messages_level == UserOption.email_level_types[:never]
    user.user_option.update!(email_messages_level: UserOption.email_level_types[:always])
  end
end

#extract_from_apple_mail(doc) ⇒ Object



573
574
575
576
577
578
# File 'lib/email/receiver.rb', line 573

def extract_from_apple_mail(doc)
  # AppleMail is the worst. It adds 'AppleMailSignature' ids (!) to several div/p with no deterministic rules
  # Our best guess is to elide whatever comes after that.
  elided = doc.css("#AppleMailSignature:last-of-type ~ *").remove
  to_markdown(doc.to_html, elided.to_html)
end

#extract_from_exchange(doc) ⇒ Object



566
567
568
569
570
571
# File 'lib/email/receiver.rb', line 566

def extract_from_exchange(doc)
  # Exchange is using the 'messageReplySection' class for forwarded emails
  # And 'messageBodySection' for the actual email
  elided = doc.css("div[name='messageReplySection']").remove
  to_markdown(doc.css("div[name='messageReplySection']").to_html, elided.to_html)
end

#extract_from_front(doc) ⇒ Object



610
611
612
613
614
# File 'lib/email/receiver.rb', line 610

def extract_from_front(doc)
  # Removes anything that has a class starting with 'front-'
  elided = doc.css("*[class^='front-']").remove
  to_markdown(doc.to_html, elided.to_html)
end

#extract_from_gmail(doc) ⇒ Object



543
544
545
546
547
# File 'lib/email/receiver.rb', line 543

def extract_from_gmail(doc)
  # GMail adds a bunch of 'gmail_' prefixed classes like: gmail_signature, gmail_extra, gmail_quote, gmail_default...
  elided = doc.css(".gmail_signature, .gmail_extra").remove
  to_markdown(doc.to_html, elided.to_html)
end

#extract_from_mozilla(doc) ⇒ Object



580
581
582
583
584
585
586
587
588
589
590
# File 'lib/email/receiver.rb', line 580

def extract_from_mozilla(doc)
  # Mozilla (Thunderbird ?) properly identifies signature and forwarded emails
  # Remove them and anything that comes after
  elided =
    doc.css(
      "*[class^='moz-cite'], *[class^='moz-cite'] ~ *, " \
        "*[class^='moz-signature'], *[class^='moz-signature'] ~ *, " \
        "*[class^='moz-forward'], *[class^='moz-forward'] ~ *",
    ).remove
  to_markdown(doc.to_html, elided.to_html)
end

#extract_from_newton(doc) ⇒ Object



604
605
606
607
608
# File 'lib/email/receiver.rb', line 604

def extract_from_newton(doc)
  # Removes anything that has an id or a class starting with 'cm_'
  elided = doc.css("*[id^='cm_'], *[class^='cm_']").remove
  to_markdown(doc.to_html, elided.to_html)
end

#extract_from_outlook(doc) ⇒ Object



549
550
551
552
553
554
# File 'lib/email/receiver.rb', line 549

def extract_from_outlook(doc)
  # Outlook properly identifies the signature and any replied/forwarded email
  # Use their id to remove them and anything that comes after
  elided = doc.css("#Signature, #Signature ~ *, hr, #divRplyFwdMsg, #divRplyFwdMsg ~ *").remove
  to_markdown(doc.to_html, elided.to_html)
end

#extract_from_protonmail(doc) ⇒ Object



592
593
594
595
596
# File 'lib/email/receiver.rb', line 592

def extract_from_protonmail(doc)
  # Removes anything that has a class starting with "protonmail_" and everything after that
  elided = doc.css("*[class^='protonmail_'], *[class^='protonmail_'] ~ *").remove
  to_markdown(doc.to_html, elided.to_html)
end

#extract_from_word(doc) ⇒ Object



556
557
558
559
560
561
562
563
564
# File 'lib/email/receiver.rb', line 556

def extract_from_word(doc)
  # Word (?) keeps the content in the 'WordSection1' class and uses <p> tags
  # When there's something else (<table>, <div>, etc..) there's high chance it's a signature or forwarded email
  elided =
    doc.css(
      ".WordSection1 > :not(p):not(ul):first-of-type, .WordSection1 > :not(p):not(ul):first-of-type ~ *",
    ).remove
  to_markdown(doc.at(".WordSection1").to_html, elided.to_html)
end

#extract_from_zimbra(doc) ⇒ Object



598
599
600
601
602
# File 'lib/email/receiver.rb', line 598

def extract_from_zimbra(doc)
  # Removes anything that has a 'data-marker' attribute
  elided = doc.css("*[data-marker]").remove
  to_markdown(doc.to_html, elided.to_html)
end

#find_existing_and_update_imapObject



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/email/receiver.rb', line 151

def find_existing_and_update_imap
  return unless incoming_email = IncomingEmail.find_by(message_id: @message_id)

  # If we are not doing this for IMAP purposes just return the record.
  return incoming_email if @opts[:imap_uid].blank?

  # If the message_id matches the post id regexp then we
  # generated the message_id not the imap server, e.g. in GroupSmtpEmail,
  # so we want to update the incoming email because it will
  # be missing IMAP details.
  #
  # Otherwise the incoming email is a completely new one from the IMAP
  # server (e.g. a message_id generated by Gmail) and does not need to
  # be updated, because message_ids from the IMAP server are not guaranteed
  # to be unique.
  return unless Email::MessageIdService.discourse_generated_message_id?(@message_id)

  incoming_email.update(
    imap_uid_validity: @opts[:imap_uid_validity],
    imap_uid: @opts[:imap_uid],
    imap_group_id: @opts[:imap_group_id],
    imap_sync: false,
  )

  incoming_email
end

#find_or_create_user(email, display_name, raise_on_failed_create: false, user: nil) ⇒ Object



793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
# File 'lib/email/receiver.rb', line 793

def find_or_create_user(email, display_name, raise_on_failed_create: false, user: nil)
  User.transaction do
    user ||= User.find_by_email(email)

    if user.nil? && SiteSetting.enable_staged_users
      raise EmailNotAllowed unless EmailValidator.allowed?(email)

      username = UserNameSuggester.sanitize_username(display_name) if display_name.present?
      begin
        user =
          User.create!(
            email: email,
            username: UserNameSuggester.suggest(username.presence || email),
            name: display_name.presence || User.suggest_name(email),
            staged: true,
          )
        @created_staged_users << user
      rescue PG::UniqueViolation, ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid
        raise if raise_on_failed_create
        user = nil
      end
    end

    @staged_users << user if user&.staged?
  end

  user
end

#find_or_create_user!(email, display_name) ⇒ Object



822
823
824
# File 'lib/email/receiver.rb', line 822

def find_or_create_user!(email, display_name)
  find_or_create_user(email, display_name, raise_on_failed_create: true)
end

#find_related_post(force: false) ⇒ Object



1244
1245
1246
1247
1248
1249
1250
1251
# File 'lib/email/receiver.rb', line 1244

def find_related_post(force: false)
  return if !force && SiteSetting.find_related_post_with_key && !sent_to_mailinglist_mirror?

  message_ids = Email::Receiver.extract_reply_message_ids(@mail, max_message_id_count: 5)
  return if message_ids.empty?

  Email::MessageIdService.find_post_from_message_ids(message_ids)
end

#fix_charset(mail_part) ⇒ Object



621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
# File 'lib/email/receiver.rb', line 621

def fix_charset(mail_part)
  return nil if mail_part.blank? || mail_part.body.blank?

  string =
    begin
      mail_part.body.decoded
    rescue StandardError
      nil
    end

  return nil if string.blank?

  # common encodings
  encodings = COMMON_ENCODINGS.dup
  encodings.unshift(mail_part.charset) if mail_part.charset.present?

  # mail (>=2.5) decodes mails with 8bit transfer encoding to utf-8, so always try UTF-8 first
  if mail_part.content_transfer_encoding == "8bit"
    encodings.delete("UTF-8")
    encodings.unshift("UTF-8")
  end

  encodings.uniq.each do |encoding|
    fixed = try_to_encode(string, encoding)
    return fixed if fixed.present?
  end

  nil
end

#forwarded_email_create_replies(destination, user) ⇒ Object



1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
# File 'lib/email/receiver.rb', line 1121

def forwarded_email_create_replies(destination, user)
  forwarded_by_address, forwarded_by_name =
    Email::Receiver.extract_email_address_and_name(@mail[:from])

  if forwarded_by_address && forwarded_by_name
    @forwarded_by_user = stage_sender_user(forwarded_by_address, forwarded_by_name)
  end

  email_address, display_name =
    parse_from_field(embedded_email, process_forwarded_emails: false)

  return false if email_address.blank? || !email_address.include?("@")

  post =
    forwarded_email_create_topic(
      destination: destination,
      user: user,
      raw: try_to_encode(embedded_email.decoded, "UTF-8").presence || embedded_email.to_s,
      title: embedded_email.subject.presence || subject,
      date: embedded_email.date,
      embedded_user: lambda { find_or_create_user(email_address, display_name) },
    )

  return false unless post

  if post.topic
    # mark post as seen for the forwarder
    PostTiming.record_timing(
      user_id: user.id,
      topic_id: post.topic_id,
      post_number: post.post_number,
      msecs: 5000,
    )

    # create reply when available
    if @before_embedded.present?
      post_type = Post.types[:regular]
      post_type = Post.types[:whisper] if post.topic.private_message? &&
        destination.usernames[user.username]

      create_reply(
        user: user,
        raw: @before_embedded,
        post: post,
        topic: post.topic,
        post_type: post_type,
        skip_validations: user.staged?,
      )
    else
      if @forwarded_by_user
        post.topic.topic_allowed_users.find_or_create_by!(user_id: @forwarded_by_user.id)
      end
      post.topic.add_small_action(@forwarded_by_user || user, "forwarded")
    end
  end

  true
end

#forwarded_email_create_topic(destination:, user:, raw:, title:, date: nil, embedded_user: nil) ⇒ Object



1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
# File 'lib/email/receiver.rb', line 1080

def forwarded_email_create_topic(
  destination:,
  user:,
  raw:,
  title:,
  date: nil,
  embedded_user: nil
)
  if destination.is_a?(Group)
    topic_user = embedded_user&.call || user
    create_topic(
      user: topic_user,
      raw: raw,
      title: title,
      archetype: Archetype.private_message,
      target_usernames: [user.username],
      target_group_names: [destination.name],
      is_group_message: true,
      skip_validations: true,
      created_at: date,
    )
  elsif destination.is_a?(Category)
    return false if user.staged? && !destination.email_in_allow_strangers
    if user.groups.any? && !user.in_any_groups?(SiteSetting.email_in_allowed_groups_map)
      return false
    end

    topic_user = embedded_user&.call || user
    create_topic(
      user: topic_user,
      raw: raw,
      title: title,
      category: destination.id,
      skip_validations: topic_user.staged?,
      created_at: date,
    )
  else
    false
  end
end

#forwarded_email_quote_forwarded(destination, user) ⇒ Object



1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
# File 'lib/email/receiver.rb', line 1180

def forwarded_email_quote_forwarded(destination, user)
  raw = <<~MD
    #{@before_embedded}

    [quote]
    #{PlainTextToMarkdown.new(@embedded_email_raw).to_markdown}
    [/quote]
  MD

  if forwarded_email_create_topic(
       destination: destination,
       user: user,
       raw: raw,
       title: subject,
     )
    true
  end
end

#forwarded_reply_key?(post_reply_key, user) ⇒ Boolean

Returns:

  • (Boolean)


1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
# File 'lib/email/receiver.rb', line 1002

def forwarded_reply_key?(post_reply_key, user)
  incoming_emails =
    IncomingEmail
      .joins(:post)
      .where("posts.topic_id = ?", post_reply_key.post.topic_id)
      .addressed_to(post_reply_key.reply_key)
      .addressed_to_user(user)
      .pluck(:to_addresses, :cc_addresses)

  incoming_emails.each do |to_addresses, cc_addresses|
    unless contains_email_address_of_user?(to_addresses, user) ||
             contains_email_address_of_user?(cc_addresses, user)
      next
    end

    if contains_reply_by_email_address(to_addresses, post_reply_key.reply_key) ||
         contains_reply_by_email_address(cc_addresses, post_reply_key.reply_key)
      return true
    end
  end

  false
end

#get_all_recipients(mail) ⇒ Object



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/email/receiver.rb', line 298

def get_all_recipients(mail)
  recipients = Set.new

  %i[to cc bcc].each do |field|
    next if mail[field].blank?

    mail[field].each do |address_field|
      begin
        address_field.decoded
        recipients << address_field.address.downcase
      end
    end
  end

  recipients
end

#group_incoming_emails_regexObject



1225
1226
1227
1228
1229
1230
1231
1232
# File 'lib/email/receiver.rb', line 1225

def group_incoming_emails_regex
  @group_incoming_emails_regex =
    Regexp.union(DB.query_single(<<~SQL).map { |e| e.split("|") }.flatten.compact_blank.uniq)
      SELECT CONCAT(incoming_email, '|', email_username)
      FROM groups
      WHERE incoming_email IS NOT NULL OR email_username IS NOT NULL
    SQL
end

#handle_bounceObject

Raises:



319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/email/receiver.rb', line 319

def handle_bounce
  @incoming_email.update_columns(is_bounce: true)
  mail_error_statuses = Array.wrap(@mail.error_status)

  if email_log.present?
    email_log.update_columns(bounced: true, bounce_error_code: mail_error_statuses.first)
    post = email_log.post
    topic = email_log.topic
  end

  DiscourseEvent.trigger(:email_bounce, @mail, @incoming_email, @email_log)

  if mail_error_statuses.any? { |s| s.start_with?(Email::SMTP_STATUS_TRANSIENT_FAILURE) }
    Email::Receiver.update_bounce_score(@from_email, SiteSetting.soft_bounce_score)
  else
    Email::Receiver.update_bounce_score(@from_email, SiteSetting.hard_bounce_score)
  end

  if SiteSetting.whispers_allowed_groups.present? && @from_user&.staged?
    return if email_log.blank?

    if post.present? && topic.present? && topic.archetype == Archetype.private_message
      body, elided = select_body
      body ||= ""

      create_reply(
        user: @from_user,
        raw: body,
        elided: elided,
        post: post,
        topic: topic,
        skip_validations: true,
        bounce: true,
      )
    end
  end

  raise BouncedEmailError
end

#has_been_forwarded?Boolean

Returns:

  • (Boolean)


1046
1047
1048
# File 'lib/email/receiver.rb', line 1046

def has_been_forwarded?
  subject[/\A[[:blank:]]*(fwd?|tr)[[:blank:]]?:/i] && embedded_email_raw.present?
end

#is_allowed?(attachment) ⇒ Boolean

Returns:

  • (Boolean)


1343
1344
1345
1346
# File 'lib/email/receiver.rb', line 1343

def is_allowed?(attachment)
  attachment.content_type !~ SiteSetting.blocked_attachment_content_types_regex &&
    attachment.filename !~ SiteSetting.blocked_attachment_filenames_regex
end

#is_auto_generated?Boolean

Returns:

  • (Boolean)


403
404
405
406
407
408
409
410
411
412
413
# File 'lib/email/receiver.rb', line 403

def is_auto_generated?
  return false if SiteSetting.auto_generated_allowlist.split("|").include?(@from_email)
  @mail[:precedence].to_s[/list|junk|bulk|auto_reply/i] ||
    @mail[:from].to_s[/(mailer[\-_]?daemon|post[\-_]?master|no[\-_]?reply)@/i] ||
    @mail[:subject].to_s[
      /\A\s*(Auto:|Automatic reply|Autosvar|Automatisk svar|Automatisch antwoord|Abwesenheitsnotiz|Risposta Non al computer|Automatisch antwoord|Auto Response|Respuesta automática|Fuori sede|Out of Office|Frånvaro|Réponse automatique)/i
    ] ||
    @mail.header.reject { |h| h.name.downcase == "x-auto-response-suppress" }.to_s[
      /auto[\-_]?(response|submitted|replied|reply|generated|respond)|holidayreply|machinegenerated/i
    ]
end

#is_blocked?Boolean

Returns:

  • (Boolean)


178
179
180
181
# File 'lib/email/receiver.rb', line 178

def is_blocked?
  return false if SiteSetting.ignore_by_title.blank?
  Regexp.new(SiteSetting.ignore_by_title, Regexp::IGNORECASE) =~ @mail.subject
end

#is_bounce?Boolean

Returns:

  • (Boolean)


315
316
317
# File 'lib/email/receiver.rb', line 315

def is_bounce?
  @mail.bounced? || bounce_key
end

#is_from_reply_by_email_address?Boolean

Returns:

  • (Boolean)


359
360
361
# File 'lib/email/receiver.rb', line 359

def is_from_reply_by_email_address?
  Email::Receiver.reply_by_email_address_regex.match(@from_email)
end

#is_spam?Boolean

Returns:

  • (Boolean)


415
416
417
418
419
420
421
422
423
424
425
426
# File 'lib/email/receiver.rb', line 415

def is_spam?
  case SiteSetting.email_in_spam_header
  when "X-Spam-Flag"
    @mail[:x_spam_flag].to_s[/YES/i]
  when "X-Spam-Status"
    @mail[:x_spam_status].to_s[/\AYes, /i]
  when "X-SES-Spam-Verdict"
    @mail[:x_ses_spam_verdict].to_s[/FAIL/i]
  else
    false
  end
end

#likesObject



1269
1270
1271
# File 'lib/email/receiver.rb', line 1269

def likes
  @likes ||= Set.new ["+1", "<3", "", I18n.t("post_action_types.like.title").downcase]
end

#log_and_validate_user(user) ⇒ Object

Raises:



291
292
293
294
295
296
# File 'lib/email/receiver.rb', line 291

def log_and_validate_user(user)
  @incoming_email.update_columns(user_id: user.id)

  raise InactiveUserError if !user.active && !user.staged
  raise SilencedUserError if user.silenced?
end

#new_group_topic_body(body, target_post, too_old_for_group_smtp) ⇒ Object



991
992
993
994
995
996
997
998
999
1000
# File 'lib/email/receiver.rb', line 991

def new_group_topic_body(body, target_post, too_old_for_group_smtp)
  return body if !too_old_for_group_smtp
  body + "\n\n----\n\n" +
    I18n.t(
      "emails.incoming.continuing_old_discussion",
      url: target_post.topic.url,
      title: target_post.topic.title,
      count: SiteSetting.disallow_reply_by_email_after_days,
    )
end

#notification_level_for(body) ⇒ Object



1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
# File 'lib/email/receiver.rb', line 1292

def notification_level_for(body)
  # since we are stripping save all this work on long replies
  return nil if body.length > 40

  body = body.strip.downcase
  case body
  when "mute"
    NotificationLevels.topic_levels[:muted]
  when "track"
    NotificationLevels.topic_levels[:tracking]
  when "watch"
    NotificationLevels.topic_levels[:watching]
  else
    nil
  end
end

#notify_about_rejected_attachment(attachments) ⇒ Object



1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
# File 'lib/email/receiver.rb', line 1452

def notify_about_rejected_attachment(attachments)
  errors = []

  attachments.each do |a|
    error = a.errors.messages.values[0][0]
    errors << "#{a.original_filename}: #{error}"
  end

  message = Mail::Message.new(@mail)
  template_args = {
    former_title: message.subject,
    destination: message.to,
    site_name: SiteSetting.title,
    rejected_errors: errors.join("\n"),
  }

  client_message =
    RejectionMailer.send_rejection(:email_reject_attachment, message.from, template_args)
  Email::Sender.new(client_message, :email_reject_attachment).send
end

#parse_from_field(mail, process_forwarded_emails: true) ⇒ Object



691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
# File 'lib/email/receiver.rb', line 691

def parse_from_field(mail, process_forwarded_emails: true)
  if email_log.present?
    email = email_log.to_address || email_log.user&.email
    return email, email_log.user&.username
  elsif mail.bounced?
    # "Final-Recipient" has a specific format (<name> ; <address>)
    # cf. https://www.ietf.org/rfc/rfc2298.html#section-3.2.4
    address_type, generic_address = mail.final_recipient.to_s.split(";").map { _1.to_s.strip }
    return generic_address, nil if generic_address.include?("@") && address_type == "rfc822"
  end

  return unless mail[:from]

  # For forwarded emails, where the from address matches a group incoming
  # email, we want to use the from address of the original email sender,
  # which we can extract from embedded_email_raw.
  if process_forwarded_emails && has_been_forwarded?
    if mail[:from].to_s =~ group_incoming_emails_regex
      if embedded_email && embedded_email[:from].errors.blank?
        from_address, from_display_name =
          Email::Receiver.extract_email_address_and_name(embedded_email[:from])
        return from_address, from_display_name if from_address
      end
    end
  end

  # extract proper sender when using mailman mailing list
  if mail[:x_mailman_version].present?
    address, name = Email::Receiver.extract_email_address_and_name_from_mailman(mail)
    return address, name if address
  end

  # For now we are only using the Reply-To header if the email has
  # been forwarded via Google Groups, which is why we are checking the
  # X-Original-From header too. In future we may want to use the Reply-To
  # header in more cases.
  if mail[:x_original_from].present? && mail[:reply_to].present?
    original_from_address, _ =
      Email::Receiver.extract_email_address_and_name(mail[:x_original_from])
    reply_to_address, reply_to_name =
      Email::Receiver.extract_email_address_and_name(mail[:reply_to])
    return reply_to_address, reply_to_name if original_from_address == reply_to_address
  end

  Email::Receiver.extract_email_address_and_name(mail[:from])
rescue StandardError
  nil
end

#post_action_for(body) ⇒ Object



1282
1283
1284
# File 'lib/email/receiver.rb', line 1282

def post_action_for(body)
  PostActionType.types[:like] if likes.include?(body.strip.downcase)
end

#previous_replies_regexObject



660
661
662
663
664
665
666
667
668
669
670
671
# File 'lib/email/receiver.rb', line 660

def previous_replies_regex
  strings =
    I18n
      .available_locales
      .map do |locale|
        I18n.with_locale(locale) { I18n.t("user_notifications.previous_discussion") }
      end
      .uniq

  @previous_replies_regex ||=
    /\A--[- ]\n\*(?:#{strings.map { |x| Regexp.escape(x) }.join("|")})\*\n/im
end

#process!Object



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/email/receiver.rb', line 121

def process!
  return if is_blocked?

  id_hash = Digest::SHA1.hexdigest(@message_id)

  DistributedMutex.synchronize("process_email_#{id_hash}") do
    begin
      # If we find an existing incoming email record with the exact same `message_id`
      # do not create a new `IncomingEmail` record to avoid double ups.
      return if @incoming_email = find_existing_and_update_imap

      Email::Validator.ensure_valid!(@mail)

      @from_email, @from_display_name = parse_from_field(@mail)
      @from_user = User.find_by_email(@from_email)
      @incoming_email = create_incoming_email

      post = process_internal

      raise BouncedEmailError if is_bounce?

      post
    rescue Exception => e
      @incoming_email.update_columns(error: e.class.name) if @incoming_email
      delete_created_staged_users
      raise
    end
  end
end

#process_destination(destination, user, body, elided) ⇒ Object



872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
# File 'lib/email/receiver.rb', line 872

def process_destination(destination, user, body, elided)
  if SiteSetting.forwarded_emails_behaviour != "hide" && has_been_forwarded? &&
       process_forwarded_email(destination, user)
    return
  end

  return if is_bounce? && !destination.is_a?(PostReplyKey)

  if destination.is_a?(Group)
    user ||= stage_from_user
    create_group_post(destination, user, body, elided)
  elsif destination.is_a?(Category)
    if (user.nil? || user.staged?) && !destination.email_in_allow_strangers
      raise StrangersNotAllowedError
    end

    user ||= stage_from_user

    if !user.staged? && !user.in_any_groups?(SiteSetting.email_in_allowed_groups_map) &&
         !sent_to_mailinglist_mirror?
      raise InsufficientTrustLevelError
    end

    create_topic(
      user: user,
      raw: body,
      elided: elided,
      title: subject,
      category: destination.id,
      skip_validations: user.staged?,
    )
  elsif destination.is_a?(PostReplyKey)
    # We don't stage new users for emails to reply addresses, exit if user is nil
    raise BadDestinationAddress if user.blank?

    post = Post.with_deleted.find(destination.post_id)
    raise ReplyNotAllowedError if !Guardian.new(user).can_create_post?(post&.topic)

    if destination.user_id != user.id && !forwarded_reply_key?(destination, user)
      raise ReplyUserNotMatchingError,
            "post_reply_key.user_id => #{destination.user_id.inspect}, user.id => #{user.id.inspect}"
    end

    create_reply(
      user: user,
      raw: body,
      elided: elided,
      post: post,
      topic: post&.topic,
      skip_validations: user.staged?,
      bounce: is_bounce?,
    )
  end
end

#process_forwarded_email(destination, user) ⇒ Object



1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
# File 'lib/email/receiver.rb', line 1068

def process_forwarded_email(destination, user)
  user ||= stage_from_user
  case SiteSetting.forwarded_emails_behaviour
  when "create_replies"
    forwarded_email_create_replies(destination, user)
  when "quote"
    forwarded_email_quote_forwarded(destination, user)
  else
    false
  end
end

#process_internalObject



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/email/receiver.rb', line 201

def process_internal
  handle_bounce if is_bounce?
  raise NoSenderDetectedError if @from_email.blank?
  raise FromReplyByAddressError if is_from_reply_by_email_address?
  raise ScreenedEmailError if ScreenedEmail.should_block?(@from_email)

  user = @from_user

  if user.present?
    log_and_validate_user(user)
  else
    raise UserNotFoundError unless SiteSetting.enable_staged_users
  end

  recipients = get_all_recipients(@mail)
  if recipients.size > SiteSetting.maximum_recipients_per_new_group_email
    raise TooManyRecipientsError.new(recipients_count: recipients.size)
  end

  body, elided = select_body
  body ||= ""

  raise NoBodyDetectedError if body.blank? && attachments.empty? && !is_bounce?

  if is_auto_generated? && !sent_to_mailinglist_mirror?
    @incoming_email.update_columns(is_auto_generated: true)

    if SiteSetting.block_auto_generated_emails? && !is_bounce? && !@opts[:allow_auto_generated]
      raise AutoGeneratedEmailError
    end
  end

  if action = subscription_action_for(body, subject)
    raise UnsubscribeNotAllowed if user.nil?
    send_subscription_mail(action, user)
    return
  end

  if post = find_related_post
    # Most of the time, it is impossible to **reply** without a reply key, so exit early
    if user.blank?
      if sent_to_mailinglist_mirror? || !SiteSetting.find_related_post_with_key
        user = stage_from_user
      elsif user.blank?
        raise BadDestinationAddress
      end
    end

    create_reply(
      user: user,
      raw: body,
      elided: elided,
      post: post,
      topic: post.topic,
      skip_validations: user.staged?,
      bounce: is_bounce?,
    )
  else
    first_exception = nil

    destinations.each do |destination|
      begin
        return process_destination(destination, user, body, elided)
      rescue => e
        first_exception ||= e
      end
    end

    raise first_exception if first_exception

    # We don't stage new users for emails to reply addresses, exit if user is nil
    raise BadDestinationAddress if user.blank?

    # We only get here if there are no destinations (the email is not going to
    # a Category, Group, or PostReplyKey)
    post = find_related_post(force: true)

    if post && Guardian.new(user).can_see_post?(post)
      if destination_too_old?(post)
        raise OldDestinationError.new("#{Discourse.base_url}/p/#{post.id}")
      end
    end

    if EmailLog.where(email_type: "digest", message_id: @mail.in_reply_to).exists?
      raise ReplyToDigestError
    end
    raise BadDestinationAddress
  end
end

#reply_above_line_regexObject



673
674
675
676
677
678
679
680
681
682
683
# File 'lib/email/receiver.rb', line 673

def reply_above_line_regex
  strings =
    I18n
      .available_locales
      .map do |locale|
        I18n.with_locale(locale) { I18n.t("user_notifications.reply_above_line") }
      end
      .uniq

  @reply_above_line_regex ||= /\n(?:#{strings.map { |x| Regexp.escape(x) }.join("|")})\n/im
end

#select_bodyObject



432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
# File 'lib/email/receiver.rb', line 432

def select_body
  text = nil
  html = nil
  text_content_type = nil

  if @mail.multipart?
    text = fix_charset(@mail.text_part)
    html = fix_charset(@mail.html_part)
    text_content_type = @mail.text_part&.content_type
  elsif @mail.content_type.to_s["text/html"]
    html = fix_charset(@mail)
  elsif @mail.content_type.blank? || @mail.content_type["text/plain"]
    text = fix_charset(@mail)
    text_content_type = @mail.content_type
  end

  return if text.blank? && html.blank?

  if text.present?
    text = trim_discourse_markers(text)
    text, elided_text = trim_reply_and_extract_elided(text)

    if @opts[:convert_plaintext] || sent_to_mailinglist_mirror?
      text_content_type ||= ""
      converter_opts = {
        format_flowed: !!(text_content_type =~ /format\s*=\s*["']?flowed["']?/i),
        delete_flowed_space: !!(text_content_type =~ /DelSp\s*=\s*["']?yes["']?/i),
      }
      text = PlainTextToMarkdown.new(text, converter_opts).to_markdown
      elided_text = PlainTextToMarkdown.new(elided_text, converter_opts).to_markdown
    end
  end

  # keep track of inlined images in html version
  # so we can later check if they were elided
  @cids = (html.presence || "").scan(/src\s*=\s*['"](cid:.+?)["']/).flatten

  markdown, elided_markdown =
    if html.present?
      # use the first html extracter that matches
      if html_extracter = HTML_EXTRACTERS.select { |_, r| html[r] }.min_by { |_, r| html =~ r }
        doc = Nokogiri::HTML5.fragment(html)
        self.public_send(:"extract_from_#{html_extracter[0]}", doc)
      else
        markdown =
          HtmlToMarkdown.new(html, keep_img_tags: true, keep_cid_imgs: true).to_markdown
        markdown = trim_discourse_markers(markdown)
        trim_reply_and_extract_elided(markdown)
      end
    end

  text_format = Receiver.formats[:plaintext]
  if text.blank? || (SiteSetting.incoming_email_prefer_html && markdown.present?)
    text, elided_text, text_format = markdown, elided_markdown, Receiver.formats[:markdown]
  end

  if SiteSetting.strip_incoming_email_lines && text.present?
    in_code = nil

    text =
      text
        .lines
        .map! do |line|
          stripped = line.strip << "\n"

          # Do not strip list items.
          if (stripped[0] == "*" || stripped[0] == "-" || stripped[0] == "+") &&
               stripped[1] == " "
            next line
          end

          # Match beginning and ending of code blocks.
          if !in_code && stripped[0..2] == "```"
            in_code = "```"
          elsif in_code == "```" && stripped[0..2] == "```"
            in_code = nil
          elsif !in_code && stripped[0..4] == "[code"
            in_code = "[code]"
          elsif in_code == "[code]" && stripped[0..6] == "[/code]"
            in_code = nil
          end

          # Strip only lines outside code blocks.
          in_code ? line : stripped
        end
        .join
  end

  [text, elided_text, text_format]
end

#send_subscription_mail(action, user) ⇒ Object



1641
1642
1643
1644
# File 'lib/email/receiver.rb', line 1641

def send_subscription_mail(action, user)
  message = SubscriptionMailer.public_send(action, user)
  Email::Sender.new(message, :subscription).send
end

#sent_to_mailinglist_mirror?Boolean

Returns:

  • (Boolean)


839
840
841
842
843
844
845
846
847
848
# File 'lib/email/receiver.rb', line 839

def sent_to_mailinglist_mirror?
  @sent_to_mailinglist_mirror ||=
    begin
      destinations.each do |destination|
        return true if destination.is_a?(Category) && destination.mailinglist_mirror?
      end

      false
    end
end

#should_invite?(email) ⇒ Boolean

Returns:

  • (Boolean)


1628
1629
1630
1631
# File 'lib/email/receiver.rb', line 1628

def should_invite?(email)
  email !~ Email::Receiver.reply_by_email_address_regex &&
    email !~ group_incoming_emails_regex && email !~ category_email_in_regex
end

#stage_from_userObject



1646
1647
1648
# File 'lib/email/receiver.rb', line 1646

def stage_from_user
  @from_user ||= stage_sender_user(@from_email, @from_display_name)
end

#stage_sender_user(email, display_name) ⇒ Object



1650
1651
1652
# File 'lib/email/receiver.rb', line 1650

def stage_sender_user(email, display_name)
  find_or_create_user!(email, display_name).tap { |u| log_and_validate_user(u) }
end

#subjectObject



784
785
786
787
788
789
790
791
# File 'lib/email/receiver.rb', line 784

def subject
  @subject ||=
    if mail_subject = @mail.subject
      mail_subject.delete("\u0000")[0..254]
    else
      I18n.t("emails.incoming.default_subject", email: @from_email)
    end
end

#subscription_action_for(body, subject) ⇒ Object



1273
1274
1275
1276
1277
1278
1279
1280
# File 'lib/email/receiver.rb', line 1273

def subscription_action_for(body, subject)
  return unless SiteSetting.unsubscribe_via_email
  return if sent_to_mailinglist_mirror?

  if ([subject, body].compact.map(&:to_s).map(&:downcase) & ["unsubscribe"]).any?
    :confirm_unsubscribe
  end
end

#to_markdown(html, elided_html) ⇒ Object



523
524
525
526
527
528
# File 'lib/email/receiver.rb', line 523

def to_markdown(html, elided_html)
  markdown = HtmlToMarkdown.new(html, keep_img_tags: true, keep_cid_imgs: true).to_markdown
  elided_markdown =
    HtmlToMarkdown.new(elided_html, keep_img_tags: true, keep_cid_imgs: true).to_markdown
  [EmailReplyTrimmer.trim(markdown), elided_markdown]
end

#trim_discourse_markers(reply) ⇒ Object



685
686
687
688
689
# File 'lib/email/receiver.rb', line 685

def trim_discourse_markers(reply)
  return "" if reply.blank?
  reply = reply.split(previous_replies_regex)[0]
  reply.split(reply_above_line_regex)[0]
end

#trim_reply_and_extract_elided(text) ⇒ Object



616
617
618
619
# File 'lib/email/receiver.rb', line 616

def trim_reply_and_extract_elided(text)
  return text, "" if @opts[:skip_trimming] || !SiteSetting.trim_incoming_emails
  EmailReplyTrimmer.trim(text, true)
end

#try_to_encode(string, encoding) ⇒ Object



651
652
653
654
655
656
657
658
# File 'lib/email/receiver.rb', line 651

def try_to_encode(string, encoding)
  encoded = string.encode("UTF-8", encoding)
  !encoded.nil? && encoded.valid_encoding? ? encoded : nil
rescue Encoding::InvalidByteSequenceError,
       Encoding::UndefinedConversionError,
       Encoding::ConverterNotFoundError
  nil
end