Email attachment sent as encoded text

837 Views Asked by At

I'm sending an email with one or more attachments, I create the email using Mail gem, here's the code

mail = Mail.new
mail.to = to
mail.subject = subject
mail.body = email_body
mail.content_type = 'text/html'
# attaching a temp file on the rails server
mail.add_file(params["file"].tempfile.path) # path e.g "/tmp/RackMultipart-some-name-text.png"
message_to_send = Google::Apis::GmailV1::Message.new(raw: mail.to_s)
response = @gmail_service.send_user_message("me", message_to_send)

but instead of sending the attached file, I get the email as a raw text with the attachment file coming as Base64 encoded string in the body of the email. Here is an example of what the received email looks like when I send attachment/s.
The mail gem documentation for attaching files doesn't say anything in particular about making any other changes except for just adding file to the mail object. Any idea about what is going on here?

1

There are 1 best solutions below

7
On BEST ANSWER

I think that in your case, the email body and attachment file are required to be sent as multipart/alternative. So when "Mail gem" is used, how about the following modification?

Modified script:

mail = Mail.new
mail.to = to
mail.subject = subject

# I added below script.
mail.part content_type: 'multipart/alternative' do |part|
  part.html_part = Mail::Part.new(body: email_body, content_type: 'text/html')
  part.text_part = Mail::Part.new(body: email_body)
end

mail.add_file(params["file"].tempfile.path)
message_to_send = Google::Apis::GmailV1::Message.new(raw: mail.to_s)
response = @gmail_service.send_user_message("me", message_to_send)

References: