Automatic exclusion from non-working email addresses

Imagine that you have a web application and one of its functions is the mass mailing of news to your users.
For some reason, part of the email addresses of users is inactive or incorrectly filled out. Would it be nice to automatically unsubscribe users from the newsletter?
You can add a special header to sent mailing messages.
Return-Path:
Notifications from the mail server about failed deliveries will be sent to this address.
As a result, the whole task boils down to reading these notifications, extracting the email address, and marking the user with this address as unavailable for distribution.
And now a real example.
In one of our applications, the mail server adds several useful lines directly to the body of such notifications:
Final-Recipient: rfc822; nonexistent@example.com
Original-Recipient: rfc822;nonexistent@example.com
Action: failed
Status: 5.1.1
For ruby, there is an IMAP client in the standard library. We connect to our "noreply@my-application.com" mailbox and read the notifications:
imap = Net::IMAP.new('mail.my-application.com', port: 993, ssl: true)
imap.login("noreply@my-application.com", "mysecretpassword")
imap.select("INBOX") # здесь может быть другая папка в ящике, куда отфильтровываются уведомления
imap.search('ALL').each do |message_id|
# чтение тела сообщения
message = imap.fetch(message_id, 'BODY[TEXT]')[0].attr['BODY[TEXT]']
match = message.match(/^Original-Recipient: rfc822;(.*)$/)
email = match[1].strip if match
# rails-зависимый код приложения для отписки пользователя от рассылки
if email
user = User.where(email: email).first
user.unsubscribe if user
end
# перемещаем уведомление в другую папку почтового ящика
imap.copy(message_id, 'Processed')
imap.store(message_id, '+FLAGS', [:Deleted])
end
imap.expunge
imap.logout
imap.disconnect
For cleanliness, you can also check the status code. The 5.XX code indicates a fatal delivery error, for example, the email address does not exist, the 4.XX code indicates a temporary error, for example, the receiving server does not respond.
This code is run periodically in the background using Resque , Delayed :: Job , cron, or any other tool used in the application. The problem is solved: the newsletter is sent only to existing working email addresses.
The task was prepared and solved in conjunction with olemskoi
PS: In your application, such notifications may not be so verbose, but you can still try to extract a non-working email anyway. For example, if you use gmail to send letters, then notifications of failed delivery from it will contain a specific header:
X-Failed-Recipients: nonexistent@example.com
which can be used.