r-lib / gmailr

Access the Gmail RESTful API from R.
https://gmailr.r-lib.org
Other
229 stars 56 forks source link

Subject becomes garbled when it contains accented character and more than 55 characters #193

Open mikeblazanin opened 10 months ago

mikeblazanin commented 10 months ago

Weird bug here. If I send an email with a subject line containing an accented character, it works fine as long as the subject is 55 characters long or less:

message <- gm_mime() |>
  gm_to("testreceive@gmail.com") |>
  gm_from("testsend@gmail.com>") |>
  gm_subject("áaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") |>
  gm_html_body("hello world")

gm_send_message(message)

When viewed in gmail, the subject line reads as intended.

But if the subject line is 56 characters long (or longer), it comes out garbled:

message <- gm_mime() |>
  gm_to("mikeblazanin@gmail.com") |>
  gm_from("Zotero Recommender <ZoteroRecommender@gmail.com>") |>
  gm_subject("áaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") |>
  gm_html_body("hello world")

gm_send_message(message)

When viewed in gmail, the subject line reads as: "=?utf-8?B?w6FhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh"

Other notes: subject lines without accents more than 55 characters do just fine. The error still appears if you create a draft then send the draft.

Session info: I'm using a cached login to set up my authorization before running the example code above

options(gargle_oauth_cache = ".gargle_cache",
        gargle_oauth_email = TRUE)

gm_auth_configure(path = "./data-raw/client_secret_abcde.json")
gm_auth(email = "testsend@gmail.com",
        token = "./data-raw/gmailr-token.rds")
jennybc commented 10 months ago

I'm not working on gmailr right now, so this is a very superficial reaction. But if you were highly motivated to look into this, I'd start by sending the same test cases directly from the Gmail API using the "Try It" feature from pages like this: https://developers.google.com/gmail/api/reference/rest/v1/users.drafts/create. That will allow you to figure out if this is an API limitation or something janky about how gmailr uses the API. No promises about what you would learn, but it would probably be productive.

itsmevictor commented 5 months ago

Might be a little late to the party and I'm also not the developer, so take my comments with a pinch of salt, but I had a similar issue with accents messing everything up.

A workaround that has worked just fine is to define this function to specify the proper encoding:

encode_subject <- function(subject) {
    sprintf("=?UTF-8?B?%s?=", base64encode(charToRaw(enc2utf8(subject))))
}

and then to use it in the email call, like this:

gm_subject(encode_subject("INSERT THE TITLE YOU'D LIKE WITH ACCENTS")).