Ruby IMAP library doesn't decode mail subject - ruby-on-rails

I have got mail message with following subject in my Gmail accout:
"400, значение, значение"
Here is the code I use to grab mail:
imap = Net::IMAP.new('imap.gmail.com', 993, true, nil, false)
imap.login(LOGIN, PASSWORD)
imap.select("INBOX")
messages = imap.search(['ALL']).map do |message_id|
msg =imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
result = {:mailbox => msg.from[0].mailbox, :host => msg.from[0].host, :subject => msg.subject, :created_at => msg.date}
imap.store(message_id, "+FLAGS", [:Deleted])
result
end
imap.expunge()
imap.logout
In msg.subject i've got following value "=?KOI8-R?B?MTAwLCDixc7ayc4sIDMwMDAgzMnU0s/X?="
It seems that IMAP haven't decoded it. Should I do I manually or IMAP library could it for me?

Mail::Encodings is really helpful here:
require 'mail'
test = "zwei plus =?ISO-8859-15?Q?zw=F6lf_ist_vierzehn?="
puts Mail::Encodings.value_decode(test)
returns
zwei plus zwölf ist vierzehn

How about using NKF?
require 'nkf'
...
result = {... :subject => NKF.nkf("-mw", msg.subject), ...}
-mw means MIME decode and utf-8 output

Related

Seeding Data from JSON API to Ruby on Rails APP

I'm getting a no implicit conversion of String into Integer error that has me stumped, and unable to import user records and seed my database with them.
So far I have no problem accessing the data, but receive an error referencing the '[]' on the line with User.find... on it
The code I'm using is as follows:
require 'net/http'
require 'uri'
require 'json'
require 'faker'
#this script imports APR user data from the zendesk api and populates
the database with it.
uri = URI.parse("https://blahsupport.zendesk.com/api/v2/users.json")
request = Net::HTTP::Get.new(uri)
request.content_type = "application/json"
request.basic_auth("blah#blah.com", "blahpass")
req_options = {
use_ssl: uri.scheme == "https",
}
#response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
puts #response.body
puts #response.message
puts #response.code
info = #response.body
info.force_encoding("utf-8")
File.write('blahusers1.json', info)
puts "File Created Successfully!"
file = File.read('blahusers1.json')
users = JSON.load(file)
users.each do |a|
User.find_or_create_by_zendesk_id(:zendesk_id => a['id'], :url => a['url'], :name => a['name'], :email => a['email'])
end
Any ideas on how I've gotten this error? Thank you for any help!
**Edit
Below is an example of the data being returned.
{"users":[{"id":333653859,"url":"https://blahblah.zendesk.com/api/v2/users/333653859.json","name":"Randy Blah","email":"randy#blah.com","created_at":"2014-08-06T14:31:24Z","updated_at":"2018-04-04T14:22:06Z","time_zone":"Pacific Time (US & Canada)","phone":null,"shared_phone_number":null,"photo":{"url":"https://aprtechsupport.zendesk.com/api/v2/attachments/68955389.json","id":68955389,"file_name":"Work.jpg","content_url":"https://aprtechsupport.zendesk.com/system/photos/6895/5389/Work.jpg","mapped_content_url":"https://blahblah.zendesk.com/system/photos/6895/5389/Work.jpg","content_type":"image/jpeg","size":2528,"width":80,"height":80,"inline":false,"thumbnails":[{"url":"https://blahblah.zendesk.com/api/v2/attachments/68955399.json","id":68955399,"file_name":"Work_thumb.jpg","content_url":"https://blahblah.zendesk.com/system/photos/6895/5389/Work_thumb.jpg","mapped_content_url":"https://blahblah.zendesk.com/system/photos/6895/5389/Work_thumb.jpg","content_type":"image/jpeg","size":2522,"width":32,"height":32,"inline":false}]},"locale_id":1,"locale":"en-US","organization_id":null,"role":"admin","verified":true,"external_id":null,"tags":[],"alias":"","active":true,"shared":false,"shared_agent":false,"last_login_at":"2018-04-04T14:21:44Z","two_factor_auth_enabled":null,"signature":"Thanks for contacting the helpdesk!\n-Randy","details":"","notes":"","role_type":null,"custom_role_id":null,"moderator":true,"ticket_restriction":null,"only_private_comments":false,"restricted_agent":false,"suspended":false,"chat_only":false,"default_group_id":21692179,"user_fields":{}}
The example data you posted has a root object users that contains the array of user objects. So when you loop users using users.each, a is actually an Array and not a user Hash like you expected.
When you try to access an element of an Array using a 'String' index, it gives you the exception – no implicit conversion of String into Integer
So, try changing
users = JSON.load(file)
to
users = JSON.load(file)['users']
to get it working like how you'd expect.

Rails Viewpoint Send-message attachments

I've incorporated viewpoint gem to send emails using Microsoft exchange services. I don't have any issues of sending plain html email. I am not able to send a email with document attached. Someone please help me in this.
please find the sample below
endpoint = "http:///.asmx"
ep_user = ""
ep_password = ""
viewclient = Viewpoint::EWSClient.new ep_user, ep_password
view_client.send_message (:subject => message.subject, :body => message.body, :body_type => "HTML")
-Raj
Solution for my problem updated on 04/27/2016
I tweaked my code in such a way to make it workable
mail(:from=>"", :to =>"", :subject => "", :doc_path => 'public/images/1.doc')
endpoint = "http:///.asmx"
ep_user = ""
ep_password = ""
viewclient = Viewpoint::EWSClient.new ep_user, ep_password
data_file = message[:doc_path].value
data = [File.open(data_file), "r"]
view_client.send_message (:subject => message.subject, :body => message.body, :body_type => "HTML", :file_attachments => data)
The send_message options hash accepts a file_attachments option as explained in the gem's code. This option should be of type Array<File>. So I guess your code would look like:
...
array_of_files = [File.join(Rails.root, 'whatever_directory', 'whatever_file.ext')]
view_client.send_message (:subject => message.subject, :body => message.body, :body_type => "HTML", :file_attachments => array_of_files)
Update:
Seems gem is broken for the case when you try to send a message with files (I think messages are just kept as drafts and not sent, only files are). So I've updated the gem to fix this case, let me know if it works correctly. Import gem from my repo like this on your Gemfile:
gem 'viewpoint', :git => 'https://github.com/durnin/Viewpoint.git'
And try the above code again. (remember to do bundle install after updating Gemfile)

Ruby on Rails mailgun send mail with API fails

I am trying to send a mail with mailgun api but I always get a BAD REQUEST 400 error. The corresponding piece of code is
data = Multimap.new
data[:from] = "Excited User <postmaster#mydomain.mailgun.org"
data[:to] = "foo#bar.com"
data[:subject] = "Hello"
data[:text] = "Testing some Mailgun awesomness!"
RestClient.post "https://api:my-key"\
"#api.mailgun.net/v3/mydomain/messages", data
If I rewrite the code as
RestClient.post "https://api:my-key"\
"#api.mailgun.net/v3/mydomain/messages",
:from => "Mailgun Sandbox <postmaster#mydomain.mailgun.org>",
:to => "foo#bar.com",
:subject => "Hello",
:text => "Testing some Mailgun awesomness!"
it works but i want to add attachements, html etc . Am I missing something here?

attaching an email message to an email rails 2.3.5 upgrading to rails 3.017

In rails 2.3.5 we were able to attach emails as attachments to other emails which were multipart emails using the following code:
recipients to
from from
subject subject
content_type "multipart/mixed"
part "text/html" do |p|
p.body = render_message("rampup_notification.text.html.erb", :mailbody => body)
end
part "text/plain" do |p|
p.body = render_message("rampup_notification.text.plain.erb", :mailbody => body)
end
email = enrollment_application.email
if email != nil && email.raw_email != nil
attachment :content_type => "message/rfc822", :filename => "icann.eml", :body => email.raw_email, :transfer_encoding => '7bit'
end
This was very temperamental to get to work with outlook, exchange etc along with other mailers.
How do I do this in rails 3?
I see: http://www.rubydoc.info/docs/rails/3.0.0/ActionMailer/Base:attachments
encoded_content = SpecialEncode(File.read('/path/to/filename.jpg'))
attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
:encoding => 'SpecialEncoding',
:content => encoded_content }
But I dont understand how to use this, is SpecialEncode a class I need to write that does 7bit encoding?
thanks
Joel
So it turns out rails 3 actionmailer is pretty smart, this seems to work fine:
#mailbody = body
attachments["icann.eml"] = {:content => email.raw_email }
mail(:to => to, :from => from, :subject => subject)

Rails: Amazon aws-ses, missing required header 'From'

Email from Ruby code is sending without any issue. But when I try to send it from Rails console, it gives the Missing required header 'From' error even From is specified in the email (Notifier), see below:
def send_email(user)
recipients "#{user.email}"
from %("Name" "<name#domain.com>")
subject "Subject Line"
content_type "text/html"
end
Here is email sending code from rails console:
ActionMailer::Base.delivery_method = :amazon_ses
ActionMailer::Base.custom_amazon_ses_mailer = AWS::SES::Base.new(:secret_access_key => 'abc', :access_key_id => '123')
Notifier.deliver_send_email
Am I missing something?
GEMS used: rails (2.3.5), aws-ses (0.4.4), mail (2.3.0)
Here is how it was fixed:
def send_email(user)
recipients "#{user.email}"
from "'First Last' <name#domain.com>" # changing the FROM format fixed it.
subject "Subject Line"
content_type "text/html"
end

Resources