4

How can I send email with BCC via GMAIL API? I send emails to TO or CC but BCC doesn't work. I use Base64.urlsafe_encode64(email.to_s)and this code create string without BCC. My working code example:

    email = Mail.new
    email.date = Time.now
    email.subject = subject
    email.to = email_array_to_email_to(to)
    email.cc = email_array_to_email_to(cc)
    email.bcc = email_array_to_email_to(bcc)
    email.reply_to = email_array_to_email_to(reply_to)
    email.html_part do
      body message
    end
    request = {
        api_method: @google_api.users.messages.to_h['gmail.users.messages.send'],
        parameters: { userId: 'me' },
        body_object: {
            raw: Base64.urlsafe_encode64(email.to_s)
        },
    }

Do I have to call again GMAIL API and send this email with thread id and BCC as TO? I use google-api-client 0.7.1

EDIT: Mail object:

#<Mail::Message:70336725981360,
Multipart: true,
Headers: <Date: Tue,
01 Dec 2015 14:09:08 +0100>,
<Reply-To: >,
<To: ["quatermain32 <my_email@gmail.com>"]>,
<Cc: ["quatermain32 <my_email@gmail.com>"]>,
<Bcc: ["my_email@gmail.com"]>,
<Subject: Test subject>,
<Content-Type: multipart/mixed>>

Mail object with to_s:

"Date: Tue, 01 Dec 2015 14:09:08 +0100\r\n
To: my_email <my_email@gmail.com>\r\n
Cc: my_email <my_email@gmail.com>\r\n
Message-ID: <565d9c6e3cf0b_058b7@Olivers-MacBook-Pro.local.mail>\r\n
Subject: Test subject\r\n
Mime-Version: 1.0\r\n
Content-Type: multipart/mixed;\r\n
 boundary=\"--==_mimepart_565d9bf468e77_cb0d35e200577a\";\r\n
 charset=UTF-8\r\n
 Content-Transfer-Encoding: 7bit\r\n
\r\n
\r\n
----==_mimepart_565d9bf468e77_cb0d3ff88645e200577a\r\n
Content-Type: text/html;\r\n
 charset=UTF-8\r\n
 Content-Transfer-Encoding: 7bit\r\n
\r\n
<p>Test content</p>\r\n
----==_mimepart_565d9bf468e77_cb0d3ff88645e200577a--\r\n
"
quatermain
  • 1,442
  • 2
  • 18
  • 33

1 Answers1

6

You have to manually add the bcc header to the email, it will not be sent to the recipients. Same as gmail-ruby-api does it https://github.com/jhk753/gmail-ruby-api/blob/e0d62a751bc31397926c5800532f26e185e00b16/lib/gmail/message.rb

encoded = mail.encoded
if bcc = mail.bcc.join(",").presence
  encoded.prepend "Bcc: #{bcc}\n"
end
... send email ...
grosser
  • 14,707
  • 7
  • 57
  • 61
  • 1
    This is the right answer. The Mail gem discards the Bcc header when you call `.encoded` on it, which is what ultimately happens during `mail.to_s`. – Al Chou Mar 19 '17 at 06:28