While processing an email reply how can I ignore any email client specifics & the history? - ruby-on-rails

I have a rails application which processes incoming emails via IMAP. Currently a method is used that searches the parts of a TMail object for a given content_type:
def self.search_parts_for_content_type(parts, content_type = 'text/html')
parts.each do |part|
if part.content_type == content_type
return part.body
else
if part.multipart?
if body = self.search_parts_for_content_type(part.parts, content_type)
return body
end
end
end
end
return false
end
These emails are generally in response to a html email it sent out in the first place. (The original outbound email is never the same.) The body text the method above returns contains the full history of the email and I would like to just parse out the reply text.
I'm wondering whether it's reasonable to place some '---please reply above this line---' text at the top of the mail as I have seen in a 37 signals application.
Is there another way to ignore the client specific additions to the email, other than write a multitude of regular expressions (which I haven't yet attempted) for each and every mail client? They all seem to tack on their own bit at the top of any replies.

I have to do email reply parsing on a project I'm working on right now. I ended up using pattern matching to identify the response part, so users wouldn't have to worry about where to insert their reply.
The good news is that the implementation really isn't too difficult. The hard part is just testing all the different email clients and services you want to support and figuring out how to identify each one. Generally, you can use either the message ID or the X-Mailer or Return-Path header to determine where an incoming email came from.
Here's a method that takes a TMail object and extracts the response part of the message and returns that along with the email client/service it was sent from. It assumes you have the original message's From: name and address in the constants FROM_NAME and FROM_ADDRESS.
def find_reply(email)
message_id = email.message_id('')
x_mailer = email.header_string('x-mailer')
# For optimization, this list could be sorted from most popular to least popular email client/service
rules = [
[ 'Gmail', lambda { message_id =~ /.+gmail\.com>\z/}, /^.*#{FROM_NAME}\s+<#{FROM_ADDRESS}>\s*wrote:.*$/ ],
[ 'Yahoo! Mail', lambda { message_id =~ /.+yahoo\.com>\z/}, /^_+\nFrom: #{FROM_NAME} <#{FROM_ADDRESS}>$/ ],
[ 'Microsoft Live Mail/Hotmail', lambda { email.header_string('return-path') =~ /<.+#(hotmail|live).com>/}, /^Date:.+\nSubject:.+\nFrom: #{FROM_ADDRESS}$/ ],
[ 'Outlook Express', lambda { x_mailer =~ /Microsoft Outlook Express/ }, /^----- Original Message -----$/ ],
[ 'Outlook', lambda { x_mailer =~ /Microsoft Office Outlook/ }, /^\s*_+\s*\nFrom: #{FROM_NAME}.*$/ ],
# TODO: other email clients/services
# Generic fallback
[ nil, lambda { true }, /^.*#{FROM_ADDRESS}.*$/ ]
]
# Default to using the whole body as the reply (maybe the user deleted the original message when they replied?)
notes = email.body
source = nil
# Try to detect which email service/client sent this message
rules.find do |r|
if r[1].call
# Try to extract the reply. If we find it, save it and cancel the search.
reply_match = email.body.match(r[2])
if reply_match
notes = email.body[0, reply_match.begin(0)]
source = r[0]
next true
end
end
end
[notes.strip, source]
end

I think you will be stuck on this one. I have been doing some stuff with emails myself in TMail recently, and what you will generally find is that an email that has an HTML part is generally structured like:
part 1 - multipart/mixed
sub part 1 - text/plain
sub part 2 - text/html
end
The email clients I have played with Outlook and Gmail both generate replies in this format, and they just generally quote the original email inline in the reply. At first I though that the 'old' parts of the original email would be separate parts, but they are actually not - the old part is just merged into the reply part.
You could search the part for a line that begins 'From: ' (as most clients generally place a header at the top of the original email text detailing who sent it etc), but its probably not guaranteed.
I don't really see anything wrong with a --- please reply above this line --- generally, its not that invasive, and could make things a lot simpler.

Related

The application goes offline when trying to send more than thousands of emails in Rails with AWS SES

I have implemented a platform using rails, and the goal is to send thousands of emails to customers with one click. The concept is that an email array runs each loop and inside each loop runs send email functionality like below.
#emails = ['abc#gmai.com', 'abc#example.com'] # More than 3 thousands
#emails.each do |email|
aws_email_sender(email, #email_subject, #email_body_html)
end
And the email function is like below:
def aws_email_sender(recipient, subject, htmlbody)
sender = "hello#example.com"
awsregion = "ap-west-1"
# The HTML body of the email.
htmlbodycontent = "#{htmlbody}"
# The email body for recipients with non-HTML email clients.
textbody = "This email was sent with Amazon SES using the AWS SDK for Ruby."
# Specify the text encoding scheme.
encoding = "UTF-8"
# Create a new SES resource and specify a region
ses = Aws::SES::Client.new(region: awsregion)
# Try to send the email.
begin
# Provide the contents of the email.
resp = ses.send_email({
destination: {
to_addresses: [recipient]
},
message: {
body: {
html: {
charset: encoding,
data: htmlbodycontent
},
text: {
charset: encoding,
data: textbody,
},
},
subject: {
charset: encoding,
data: subject,
},
},
source: sender,
});
# If something goes wrong, display an error message.
rescue Aws::SES::Errors::ServiceError => error
puts "Email not sent. Error message: #{error}"
end
end
The email is sending well by AWS but my rails application has gone down like
A timeout occurred, error code 524
I couldn't get the breaking point, why has my application gone down every time?
Thanks in Advance
If 524 is an HTTP status code then it means...
Cloudflare was able to make a TCP connection to the website behind them, but it did not reply with an HTTP response before the connection timed out.
Meaning your Rails app is behind a Cloudflare proxy. Cloudflare received an HTTP request, forwarded it to your app, waited around for your app to respond, but your app never did. A more detailed explanation can be found here.
Probably because it's trying to send emails to 3000 people one-by-one.
There's two strategies to fix this.
Use Bulk Email
Since the content of the email is the same for everyone, use an email template to send bulk email using the #send_bulk_templated_email method.
You can send to up to 50 addresses at a time, so use #each_slice to loop through emails in slices of 50.
This will be more efficient, but your app will still be waiting around for 3000/50 = 60 AWS API calls. At worst it will still time out. At best the user will be waiting around for a form submission.
Use A Background Job
Anytime your app needs to do something that might take a lot of time, like using a service or a large database query, consider putting it into a background job. The Rails app queues up a job to send the emails, and then it can respond to the web request while the mailing is handled in the background. This has other advantages: errors calling the service won't cause an error for the user, and failed jobs due to a temporary service outage can automatically be retried.
In Rails this is done with ActiveJob and you could write a job class to send your mail.
Use ActionMailer
However, Rails also offers a class specifically for sending email in the background: ActionMailer. You can have ActionMailer use AWS with the aws-sdk-rails gem.
config.action_mailer.delivery_method = :ses

Gmail API, Reply to thread not working / forwarding

I'm using the google gmail api in swift. All is working well, it's compiling etc.
I'm now trying forward an email, the only way I see this possible so far is by using a thread id.
So I'm using the API tester found here to send tests. Will will focus on this. It can be found here1
So I've input this, the "raw" is Base64 URL encoded string.
{
"raw": "VG86ICBlbWFpbFRvU2VuZFRvQGdtYWlsLmNvbSAKU3ViamVjdDogIFRoZSBzdWJqZWN0IHRlc3QKSW4tUmVwbHktVG86ICBteUVtYWlsQGdtYWlsLmNvbQpUaHJlYWRJZDogIDE1YjkwYWU2MzczNDQ0MTIKClNvbWUgQ29vbCB0aGluZyBpIHdhbnQgdG8gcmVwbHkgdG8geW91ciBjb252by4u",
"threadId": "15b90ae637344412"
}
The "raw" in plain text is
To: emailToSendTo#gmail.com
Subject: The subject test
In-Reply-To: myEmail#gmail.com
ThreadId: 15b90ae637344412
Some Cool thing i want to reply to your convo..
when I execute it I get this back
{
"id": "15b944f6540396df",
"threadId": "15b90ae637344412",
"labelIds": [
"SENT"
]
}
But when I check both email account, from and to. None of them say the previous messages but are in the same "thread" or convo.
If anyone can help it would be much appreciated I've spent all day on this issue and half of yesterday and did TONS of research on it.
as stated here I should I'm adding the threaded and In-Reply-To in the right way I believe
The ID of the thread the message belongs to. To add a message or draft to a thread, the following criteria must be met:
The requested threadId must be specified on the Message or Draft.Message you supply with your request.
The References and In-Reply-To headers must be set in compliance with the RFC 2822 standard.
The Subject headers must match.

The stratigy of build a talk-to-talk system using em-websocket in rails?

Maybe it is a good example for server push system. There are many users in the system, and users can talk with each other. It can be accomplished like this: one user sends message(through websocket) to the server, then the server forward the message to the other user. The key is to find the binding between the ws(websocket object) and the user. The example code like below:
EM.run {
EM::WebSocket.run(:host => "0.0.0.0", :port => 8080, :debug => false) do |ws|
ws.onopen { |handshake|
# extract the user id from handshake and store the binding between user and ws
}
ws.onmessage { |msg|
# extract the text and receiver id from msg
# extract the ws_receiver from the binding
ws_receiver.send(text)
}
end
}
I want to figure out following issues:
The ws object can be serialized so it can be stored into disk or database? Otherwise I can only store the binding into memory.
What the differences between em-websocket and websocket-rails?
Which gem do you recommend for websocket?
You're approaching a use case that websockets are pretty good for, so you're on the right track.
You could serialize the ws object with Marshal, but think of websocket objects as being a bit like http request objects in that they are abstractions for a type of communication. You are probably best off marshaling/storing the data.
em-websocket is a lower(ish) lever websocket library built more or less directly on web-machine. websocket-rails is a higher level abstraction on websockets, with a lot of nice tools built in and pretty ok docs. It is built on top of faye-websocket-rails which is itself built on web machine. *Note, action cable which is the new websocket library for Rails 5 is built on faye.
I've use websocket-rails in the past and rather like it. It will take care of a lot for you. However, if you can use Rails 5 and Action Cable, do that, its the future.
The following is in addition to Chase Gilliam's succinct answer which included references to em-websocket, websocket-rails (which hadn't been maintained in a long while), faye-websocket-rails and ActionCable.
I would recommend the Plezi framework. It works both as an independent application framework as well as a Rails Websocket enhancement.
I would consider the following points as well:
do you need the message to persist between connections (i.e. if the other user if offline, should the message wait in a "message box"? for how long should the message wait?)...?
Do you wish to preserve message history?
These points would help yo decide if to use a persistent storage (i.e. a database) for the messages or not.
i.e., to use Plezi with Rails, create an init_plezi.rb in your application's config/initializers folder. use (as an example) the following code:
class ChatDemo
# use JSON events instead of raw websockets
#auto_dispatch = true
protected #protected functions are hidden from regular Http requests
def auth msg
#user = User.auth_token(msg['token'])
return close unless #user
# creates a websocket "mailbox" that will remain open for 9 hours.
register_as #user.id, lifetime: 60*60*9, max_connections: 5
end
def chat msg, received = false
unless #user # require authentication first
close
return false
end
if received
# this is only true when we sent the message
# using the `broadcast` or `notify` methods
write msg # writes to the client websocket
end
msg['from'] = #user.id
msg['time'] = Plezi.time # an existing time object
unless msg['to'] && registered?(msg['to'])
# send an error message event
return {event: :err, data: 'No recipient or recipient invalid'}.to_json
end
# everything was good, let's send the message and inform
# this will invoke the `chat` event on the other websocket
# notice the `true` is setting the `received` flag.
notify msg['to'], :chat, msg, true
# returning a String will send it to the client
# when using the auto-dispatch feature
{event: 'message_sent', msg: msg}.to_json
end
end
# remember our route for websocket connections.
route '/ws_chat', ChatDemo
# a route to the Javascript client (optional)
route '/ws/client.js', :client
Plezi sets up it's own server (Iodine, a Ruby server), so remember to remove from your application any references to puma, thin or any other custom server.
On the client side you might want to use the Javascript helper provided by Plezi (it's optional)... add:
<script src='/es/client.js' />
<script>
TOKEN = <%= #user.token %>;
c = new PleziClient(PleziClient.origin + "/ws_chat") // the client helper
c.log_events = true // debug
c.chat = function(event) {
// do what you need to print a received message to the screen
// `event` is the JSON data. i.e.: event.event == 'chat'
}
c.error = function(event) {
// do what you need to print a received message to the screen
alert(event.data);
}
c.message_sent = function(event) {
// invoked after the message was sent
}
// authenticate once connection is established
c.onopen = function(event) {
c.emit({event: 'auth', token: TOKEN});
}
// // to send a chat message:
// c.emit{event: 'chat', to: 8, data: "my chat message"}
</script>
I didn't test the actual message code because it's just a skeleton and also it requires a Rails app with a User model and a token that I didn't want to edit just to answer a question (no offense).

How to get RSVP buttons through Icalendar gem

So I've got the Icalendar gem in my ruby project. I'm attempting to get the RSVP buttons of Yes/No/Maybe on the invite but whenever it gets sent I only get a "Add to Calendar".
Was wondering what else I need:
def make_ical_appointment(start_time, end_time, uid, email_one, email_two)
ical = Icalendar::Calendar.new
ical.timezone.tzid = "UTC"
e = Icalendar::Event.new
e.dtstart = start_time
e.dtend = end_time
e.organizer = %W(mailto:#{email_one} mailto#{email_two})
e.uid = uid
ical.add_event(e)
ical.publish
mail.attachments['appointment.ics'] = { mime_type: 'application/ics', content: ical.to_ical }
end
I've read that people need to set it to METHOD:REQUEST, but I'm not sure where to do there. I've also read that you need to set attendees, but it seems you can only set attendees if you have an alarm?
Just looking to get it to look like a regular invite.
There's two things you need to do to solve your problem:
Read RFC-2445, which defines the iCal format. It looks like section 4.8.4.1, which discusses the ATTENDEE property, and 4.2.17, which discusses the RSVP parameter, will be of particular interest.
Look at emails and .ics files you've received that display correctly in various email clients.
The page I linked to in my comment above has three hints.
The first hint
I tried adding this property:calendar.custom_property("METHOD", "REQUEST").[1]
From the docs I think that's supposed to be append_custom_property.
Opening up an invite someone sent me from Google calendar, I found this line:
METHOD:REQUEST
So that seems legit.
The second hint
I would guess that you need to add an ATTENDEE property with RSVP=TRUE and the email set to the same email that Outlook or Yahoo link to their users.[2]
In the same invite I found this:
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=
TRUE;CN=Firstname Lastname;X-NUM-GUESTS=0:mailto:jordan#example.com
I didn't read the whole RFC, but I think it breaks down like this:
ATTENDEE is the property name.
Everything between the first ; and the first : are parameters. Each of them are documented in the RFC, and I don't know if all of them are required, but we can see the RSVP=TRUE parameter there.
Everything after the first :, i.e. mailto:jordan#example.com is the value
Looking at the source of append_custom_property we see that it checks if value is an Icalendar::Value object, and if not it creates one with Icalendar::Values::Text.new(value). Since we have parameters in addition to a value, let's check out that constructor here. We see that it can take a second argument, which is a params Hash.
Now, I haven't tested it, but that suggests to me that you can build a line like the above with code something like the following†:
attendee_params = { "CUTYPE" => "INDIVIDUAL",
"ROLE" => "REQ-PARTICIPANT",
"PARTSTAT" => "NEEDS-ACTION",
"RSVP" => "TRUE",
"CN" => "Firstname Lastname",
"X-NUM-GUESTS" => "0" }
attendee_value = Icalendar::Values::Text.new("MAILTO:jordan#example.com", attendee_params)
ical.append_custom_property("ATTENDEE", attendee_value)
Edit: In Icalendar 2.x it looks like you can also do:
attendee_value = Icalendar::Values::CalAddress.new("MAILTO:jordan#example.com", attendee_params)
ical.append_attendee(attendee_value)
The CalAddress class is a subclass of Uri, which just runs the given value through URI.parse, and append_attendee appears to be a shortcut for append_custom_property("ATTENDEE", ...).
I'm not sure if all of those parameters are actually required, but you can learn what each of them is by reading the RFC.
The third hint
What I had to do to make it work in all mail clients was to send it as a multipart/alternative message with the ical as an alternative view instead of as an attachment.[3]
Sure enough, doing "Show Original" in Gmail I saw that the invite email I got is a multipart email, with a text/calendar part:
--047d7b0721581f7baa050a6c3dc0
Content-Type: text/calendar; charset=UTF-8; method=REQUEST
Content-Transfer-Encoding: 7bit
BEGIN:VCALENDAR
PRODID:-//Google Inc//Google Calendar 70.9054//EN
...
...and an application/ics attachment part:
--047d7b0721581f7bae050a6c3dc2
Content-Type: application/ics; name="invite.ics"
Content-Disposition: attachment; filename="invite.ics"
Content-Transfer-Encoding: base64
QkVHSU46VkNBTEVOREFSDQpQUk9ESUQ6LS8vR29vZ2xlIEluYy8vR29vZ2xlIENhbGVuZGFyIDcw
...
The second part you've already got, thanks to mail.attachments. For the first part, you just have to create a new Mail::Part with the correct content_type and add it to mail.parts, which will look something like this:
ical_part = Mail::Part.new do
content_type "text/calendar; charset=UTF-8; method=REQUEST"
body ical.to_ical
end
mail.add_part(ical_part)
That's all I've got. Again, I've tested none of this, and I'm not certain it'll fix your problem, but hopefully it gives you a few ideas.
The most important thing, I think, is to look at the source of emails (if you use Gmail, "Show Original" is under the drop-down menu next to the Reply button) with invites and look at how they're constructed, and likewise look at the .ics attachments and see whether or not they match what you're generating.
Good luck!
†Judging by the way Icalendar transforms the params hash into iCal parameters, I think you can use symbol keys, too, like so:
attendee_params = { cutype: "INDIVIDUAL",
role: "REQ-PARTICIPANT",
partstat: "NEEDS-ACTION",
rsvp: "TRUE",
cn: "Firstname Lastname",
x_num_guests: "0" }

Read Gmail XOAUTH mails without marking it read

I'm trying to read email from GMail using gmail-xoauth Gem. I want to read the email and leave its unread status.
First, I tried reading just the header. Works.
imap = Net::IMAP.new('imap.gmail.com', 993, usessl = true, certs = nil, verify = false)
imap.authenticate('XOAUTH2', email, access_token)
imap.select('INBOX')
imap.search(["SINCE", since]).each do |message_id|
msg = imap.fetch(message_id,'RFC822.HEADER')[0].attr['RFC822.HEADER']
mail = Mail.read_from_string msg
puts mail.subject
end
Now, I want to read the body/text of the Email without marking it read.
This maybe be very late but I will leave it here for anyone else that stumbles onto this. If, for what ever reason you want to read the email and leave the flags intake, use:
imap.examine('INBOX')
instead of:
imap.select('INBOX')
From the Net::IMAP doc
Sends a EXAMINE command to select a mailbox so that messages in the mailbox can be accessed. Behaves the same as select(), except that the selected mailbox is identified as read-only.
Based on the documentation you need to use the store method. The documentation mentions:
store(set, attr, flags)
Sends a STORE command to alter data associated with messages in the mailbox, in particular their flags. The set parameter is a number or an array of numbers or a Range object. Each number is a message sequence number. attr is the name of a data item to store: ‘FLAGS’ means to replace the message’s flag list with the provided one; ‘+FLAGS’ means to add the provided flags; and ‘-FLAGS’ means to remove them. flags is a list of flags.
The return value is an array of Net::IMAP::FetchData. For example:
p imap.store(6..8, "+FLAGS", [:Deleted])
#=> [#<Net::IMAP::FetchData seqno=6, attr={"FLAGS"=>[:Seen, :Deleted]}>, \\
#<Net::IMAP::FetchData seqno=7, attr={"FLAGS"=>[:Seen, :Deleted]}>, \\
#<Net::IMAP::FetchData seqno=8, attr={"FLAGS"=>[:Seen, :Deleted]}>]
So you have to remove the :Seen flag
imap.store(message_id, "-FLAGS", [:Seen])

Resources