verify.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. module EmailHelper
  2. class Verify
  3. =begin
  4. get result of inbound probe
  5. result = EmailHelper::Verify.email(
  6. inbound: {
  7. adapter: 'imap',
  8. options: {
  9. host: 'imap.gmail.com',
  10. port: 993,
  11. ssl: true,
  12. user: 'some@example.com',
  13. password: 'password',
  14. },
  15. },
  16. outbound: {
  17. adapter: 'smtp',
  18. options: {
  19. host: 'smtp.gmail.com',
  20. port: 25,
  21. ssl: true,
  22. user: 'some@example.com',
  23. password: 'password',
  24. },
  25. },
  26. sender: 'sender_and_recipient_of_verify_email@example.com',
  27. )
  28. returns on success
  29. {
  30. result: 'ok'
  31. }
  32. returns on fail
  33. {
  34. result: 'invalid',
  35. message: 'Verification Email not found in mailbox.',
  36. subject: subject,
  37. }
  38. or
  39. {
  40. result: 'invalid',
  41. message: 'Authentication failed!.',
  42. subject: subject,
  43. }
  44. =end
  45. def self.email(params)
  46. # send verify email
  47. subject = if params[:subject].blank?
  48. '#' + rand(99_999_999_999).to_s
  49. else
  50. params[:subject]
  51. end
  52. result = EmailHelper::Probe.outbound(params[:outbound], params[:sender], subject)
  53. if result[:result] != 'ok'
  54. result[:source] = 'outbound'
  55. return result
  56. end
  57. # validate adapter
  58. adapter = params[:inbound][:adapter].downcase
  59. if !EmailHelper.available_driver[:inbound][adapter.to_sym]
  60. return {
  61. result: 'failed',
  62. message: "Unknown adapter '#{adapter}'",
  63. }
  64. end
  65. # looking for verify email
  66. 9.times do
  67. sleep 5
  68. # fetch mailbox
  69. fetch_result = nil
  70. begin
  71. require "channel/driver/#{adapter.to_filename}"
  72. driver_class = Object.const_get("Channel::Driver::#{adapter.to_classname}")
  73. driver_instance = driver_class.new
  74. fetch_result = driver_instance.fetch(params[:inbound][:options], self, 'verify', subject)
  75. rescue => e
  76. result = {
  77. result: 'invalid',
  78. source: 'inbound',
  79. message: e.to_s,
  80. message_human: EmailHelper::Probe.translation(e.message),
  81. invalid_field: EmailHelper::Probe.invalid_field(e.message),
  82. subject: subject,
  83. }
  84. return result
  85. end
  86. next if !fetch_result
  87. next if fetch_result[:result] != 'ok'
  88. return fetch_result
  89. end
  90. {
  91. result: 'invalid',
  92. message: 'Verification Email not found in mailbox.',
  93. subject: subject,
  94. }
  95. end
  96. end
  97. end