Mailman多次保存邮件

时间:2014-01-29 21:09:17

标签: ruby-on-rails capistrano daemon mailman-gem

我已将mailman gem集成到我的rails项目中。它成功地从gmail中获取电子邮件。在我的应用程序中,我的电子邮件中有一个模型消息。电子邮件已正确保存为消息模型。

问题是电子邮件有时会被多次保存,我无法识别模式。有些电子邮件会被保存一次,有的会被保存两次,有些会被保存三次。

但我在代码中找不到失败。

这是我的mailman_server脚本:

脚本/ mailman_server

#!/usr/bin/env ruby
# encoding: UTF-8
require "rubygems"
require "bundler/setup"
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'environment'))
require 'mailman'

Mailman.config.ignore_stdin = true
#Mailman.config.logger = Logger.new File.expand_path("../../log/mailman_#{Rails.env}.log", __FILE__)

if Rails.env == 'test'
  Mailman.config.maildir = File.expand_path("../../tmp/test_maildir", __FILE__)
else
  Mailman.config.logger = Logger.new File.expand_path("../../log/mailman_#{Rails.env}.log", __FILE__)
  Mailman.config.poll_interval = 15
  Mailman.config.imap = {
    server: 'imap.gmail.com',
    port: 993,  # usually 995, 993 for gmail
    ssl: true,
    username: 'my@email.com',
    password: 'my_password'
  }
end

Mailman::Application.run do
  default do
    begin
      Message.receive_message(message)
    rescue Exception => e
      Mailman.logger.error "Exception occurred while receiving message:\n#{message}"
      Mailman.logger.error [e, *e.backtrace].join("\n")
    end
  end
end

电子邮件在我的Message类中处理:

  def self.receive_message(message)
    if message.from.first == "my@email.com"
      Message.save_bcc_mail(message)
    else
      Message.save_incoming_mail(message)
    end
  end

  def self.save_incoming_mail(message)
    part_to_use = message.html_part || message.text_part || message
    if Kontakt.where(:email => message.from.first).empty?
      encoding = part_to_use.content_type_parameters['charset']
      Message.create topic: message.subject, message: part_to_use.body.decoded.force_encoding(encoding).encode('UTF-8'), communication_partner: message.from.first, inbound: true, time: message.date
    else
      encoding = part_to_use.content_type_parameters['charset']
      Message.create topic: message.subject, message: part_to_use.body.decoded.force_encoding(encoding).encode('UTF-8'), communication_partner: message.from.first, inbound: true, time: message.date, messageable_type: 'Company', messageable_id: Kontakt.where(:email => message.from.first).first.year.id
    end
  end

  def self.save_bcc_mail(message)
    part_to_use = message.html_part || message.text_part || message
    if Kontakt.where(:email => message.to.first).empty?
      encoding = part_to_use.content_type_parameters['charset']
      Message.create topic: message.subject, message: part_to_use.body.decoded.force_encoding(encoding).encode('UTF-8'), communication_partner: message.to.first, inbound: false, time: message.date
    else
      encoding = part_to_use.content_type_parameters['charset']
      Message.create topic: message.subject, message: part_to_use.body.decoded.force_encoding(encoding).encode('UTF-8'), communication_partner: message.to.first, inbound: false, time: message.date, messageable_type: 'Company', messageable_id: Kontakt.where(:email => message.to.first).first.year.id
    end
  end

我已使用此脚本守护mailman_server:

脚本/ mailman_daemon

#!/usr/bin/env ruby

require 'rubygems'  
require "bundler/setup"  
require 'daemons'

Daemons.run('script/mailman_server') 

我使用capistrano进行部署。

这是负责停止,启动和重启mailman_server的部分:

脚本/ deploy.rb

set :rails_env, "production" #added for delayed job  
after "deploy:stop",    "delayed_job:stop"
after "deploy:start",   "delayed_job:start"
after "deploy:restart", "delayed_job:restart"
after "deploy:stop",    "mailman:stop"
after "deploy:start",   "mailman:start"
after "deploy:restart", "mailman:restart"

namespace :deploy do
  desc "mailman script ausfuehrbar machen"
  task :mailman_executable, :roles => :app do
   run "chmod +x #{current_path}/script/mailman_server"
  end

  desc "mailman daemon ausfuehrbar machen"
  task :mailman_daemon_executable, :roles => :app do
   run "chmod +x #{current_path}/script/mailman_daemon"
  end
end

namespace :mailman do  
  desc "Mailman::Start"
  task :start, :roles => [:app] do
   run "cd #{current_path};RAILS_ENV=#{fetch(:rails_env)} bundle exec script/mailman_daemon start"
  end

  desc "Mailman::Stop"
  task :stop, :roles => [:app] do
   run "cd #{current_path};RAILS_ENV=#{fetch(:rails_env)} bundle exec script/mailman_daemon stop"
  end

  desc "Mailman::Restart"
  task :restart, :roles => [:app] do
   mailman.stop
   mailman.start
  end
end

可能是我的部署期间几乎同时启动了多个邮件服务器实例,然后每个实例几乎同时进行轮询?第一个实例之前的第二个和第三个实例池将电子邮件标记为已读并轮询并处理该电子邮件?

更新30.01。

我已将轮询间隔设置为60秒。但这没有任何改变。

我检查了存储mailman pid文件的文件夹。只有一个邮递员的pid文件。所以肯定只有一个邮件服务器在运行。我检查了日志文件,可以看到,多次提取消息:

Mailman v0.7.0 started
IMAP receiver enabled (my@email.com).
Polling enabled. Checking every 60 seconds.
Got new message from 'my.other@email.com' with subject 'Test nr 0'.
Got new message from 'my.other@email.com' with subject 'Test nr 1'.
Got new message from 'my.other@email.com' with subject 'test nr 2'.
Got new message from 'my.other@email.com' with subject 'test nr 2'.
Got new message from 'my.other@email.com' with subject 'test nr 3'.
Got new message from 'my.other@email.com' with subject 'test nr 4'.
Got new message from 'my.other@email.com' with subject 'test nr 4'.
Got new message from 'my.other@email.com' with subject 'test nr 4'.

所以在我看来,问题肯定在我的邮件服务器代码中。

更新31.1。

对我来说,这与我的生产机器有关。当我在开发中使用完全相同的配置测试它时(今天早上将我的本地数据库从sqlite更改为mysql以进行测试),因为在生产机器上我没有重复。我的代码可能一切正常,但生产机器存在问题。请问我的主机是否可以看到解决方案。为了解决这个问题,我将采用Ariejan的建议。

解决方案: 我发现了这个问题。我部署到一台机器,其中tmp目录是所有版本之间的共享目录。我忘了定义应该保存mailman_daemon的pid文件的路径。所以它保存在脚本目录而不是/ tmp / pids目录中。因此,在新部署后无法停止旧的mailman_daemon。这导致了一群工作的mailman_daemons正在调查我的mailaccount ...杀死所有这些进程后一切顺利!没有更多的重复!

2 个答案:

答案 0 :(得分:2)

这可能是一些并发/计时问题。例如。在保存当前处理的新邮件之前导入新邮件。


编辑:刚刚注意到您已将Mailman.config.poll_interval设置为15.这意味着它将每15秒检查一次新邮件。尝试将此值增加到默认值60秒。无论此设置如何,添加我在下面提到的重复数据删除代码可能是个好主意。


我的建议是还要存储每封电子邮件中的message_id,以便您轻松查看重复项。

而不是:

Message.create(...)

做的:

# This makes sure you have the latest pulled version.
message = Message.find_or_create(message_id: message.message_id)
message.update_attributes(...)

# This makes sure you only import it once, then ignore further duplicates.
if !Message.where(message_id: message.message_id).exists?
  Message.create(...)
end

有关message_id的更多信息:http://rdoc.info/github/mikel/mail/Mail/Message#message_id-instance_method

请记住,电子邮件和imap并不意味着像Postgres或Mysql那样是一致的数据存储。希望这有助于您整理重复的邮件。

答案 1 :(得分:0)

我发现了问题。我部署到一台机器,其中tmp目录是所有版本之间的共享目录。我忘了定义应该保存mailman_daemon的pid文件的路径。所以它保存在脚本目录而不是/ tmp / pids目录中。因此,在新部署后无法停止旧的mailman_daemon。这导致了一群工作的mailman_daemons正在调查我的mailaccount ...杀死所有这些进程后一切顺利!没有更多的重复!