DEV Community

Yoshi
Yoshi

Posted on

Let's Stick to GmailApp Over MailApp in Google Apps Script

In Google Apps Script (GAS), there are two standard services for sending emails: MailApp and GmailApp. Both features are built-in and can be used immediately in your code without any library setup.

As mentioned in the title, when I initially used MailApp to implement an external email notification function for a report, emails to domains outside the organization resulted in bounces. After struggling with this and doing some research, I ultimately just switched to GmailApp, and the emails were sent smoothly.

This experience gave me a deeper understanding of MailApp, GmailApp, and the domain authentication mechanism known as DMARC. I'm leaving this as a memorandum for future reference.

MailApp or GmailApp: Which is Better?

The features and suggested use cases for the standard GAS email services are as follows.
As the title suggests, in practical terms, you should prioritize GmailApp if you can use it.

Item MailApp GmailApp
Sending Path Sends anonymously using a shared Google server Sends directly using the script-executing user's Gmail account
Benefits - Basic email sending is possible
- Narrow scope, requires minimal permission granting
- Reliable external sending is possible
- Allows advanced sending like aliases (alternate addresses), HTML emails, and attachments
Drawbacks - Prone to bouncing on external servers - Requires granting a broad range of user permissions

MailApp is a simple communication method designed for the purpose of "just sending an email" with minimal permissions. Because of this, external servers with strict security checks tend to regard the sender as anonymous and are more likely to reject (bounce) the email.

GmailApp sends the email from the user's authenticated mailbox (Sent folder), which gives it higher sending reliability and reduces the risk of bounces. However, using it requires broad permissions to access the user's entire Gmail data.

My initial use of MailApp in this case was simply because "it doesn't show a huge authorization UI for granting Gmail access." I thought simplifying the user flow might reduce the need for user explanations or support inquiries.

You might consider using MailApp if the email recipients are all within the same domain (for a fully internal report) or if permission management is so strict that granting Gmail data access is absolutely not possible. Otherwise, using GmailApp is less likely to cause trouble.

Why Did the Emails Bounce?

As mentioned, emails sent via MailApp were rejected when sent externally, and this is due to a mechanism called DMARC (Domain-based Message Authentication, Reporting, and Conformance). Furthermore, DMARC acts like a supervisor that leverages the results of two authentication methods, SPF and DKIM, to determine the final processing (action).

Therefore, we must first understand SPF and DKIM, which are responsible for the actual authentication process.

Both are authentication technologies designed to prevent "spoofed emails," but they fundamentally differ in what they verify.

Authentication Technology Verification Target Mechanism Analogy
SPF (Sender Policy Framework) Validity of the Sender's IP Address Checks if the postal "sender address" is on the list of allowed sources for that address.
DKIM (DomainKeys Identified Mail) Validity of the Email Content Checks if the postal "envelope" has a digital signature applied by the domain (sender) and if it hasn't been tampered with during transit.

SPF (Sender Policy Framework): Verification of the Sender's IP Address

spf

  1. Sender's Setup: The administrator of the sending domain publishes a special text record called an SPF record on the DNS server.

  2. SPF Record: This record specifies that "emails for this domain are only permitted to be sent from mail servers with IP addresses listed in this record."

  3. Recipient's Verification: The receiving server checks the domain in the Envelope From (Return-Path) field in the email header and queries the DNS for that domain's SPF record.

  4. Authentication: If the IP address of the server that actually sent the email is included in the allowed list of the SPF record, the result is Pass.

DKIM (DomainKeys Identified Mail): Verification by Digital Signature

dkim

  1. Sender's Setup: The administrator of the sending domain registers a public key on the DNS server and stores a private key on the mail sending server.

  2. Signature Application: The sending server uses the private key to encrypt part of the email header and body, and attaches that encrypted data (a digital signature) to the email header.

  3. Recipient's Verification: The receiving server checks the signature in the header and queries the DNS for the public key associated with the domain used for the signature.

  4. Authentication: The digital signature is decrypted with the public key. If it matches the original email content, the result is Pass. If it does not match (e.g., if the content was tampered with), the result is Fail.

DMARC and the SPF/DKIM Relationship

DMARC is the framework that utilizes the authentication results of SPF and DKIM to determine the final processing (action).

  1. Alignment Check: DMARC's most critical function is to check if the domain used for SPF or DKIM authentication aligns with the domain in the From address that the user sees in their email client.

  2. Policy Setting: The sending domain's administrator publishes a DMARC policy on the DNS, instructing the recipient on "how to handle emails that fail the SPF and DKIM alignment check." The policy primarily includes the following three options:

   - p=none: Take no action and send a report to the sender.
   - p=quarantine: Place the email in the spam folder (quarantine).
   - p=reject: Refuse to accept the email (bounce it).

  1. Reporting Feature: DMARC sends detailed reports (DSN reports) to the sending domain's administrator about failed authentications, including where the emails came from. This allows for a grasp of the spoofing situation and improvement of authentication settings.

In conclusion, SPF and DKIM are the individual authentication "tools," while DMARC acts as the "rulebook" that synthesizes the results from those tools to ultimately decide and control "whether to accept, discard, or how to process this email."

Tools Used for the Investigation

Here are the tools I utilized during this investigation.

  1. Email Log Search
  2. Accessed from the Admin console with Google Workspace Admin privileges.
  3. Allows checking the delivery status of a selected email.

log search

  1. SPF Record Check Tool
  2. Used mxtoolbox.com.
  3. An easy way to check the publicly available DNS information for an SPF record.

mxtool

  1. DMARC Aggregate Report
  2. Set up a custom DNS record with the value: "v=DMARC1; p=none; rua=mailto:admin@example.com".
  3. When an email is bounced, a report detailing the rejection reason, similar to the one below, is sent to admin@example.com.
<feedback>
  <version>1.0</version>
  <report_metadata>
    <org_name>google.com</org_name>
    <email>noreply-dmarc-support@google.com</email>
    <extra_contact_info>[https://support.google.com/a/answer/2466580](https://support.google.com/a/answer/2466580)</extra_contact_info>
    <report_id>7457835210456705671</report_id>
    <date_range>
      <begin>1762387200</begin>
      <end>1762473599</end>
    </date_range>
  </report_metadata>

  <policy_published>
    <domain>sample.com</domain>
    <adkim>r</adkim>
    <aspf>r</aspf>
    <p>none</p>
    <sp>none</sp>
    <pct>100</pct>
    <np>none</np>
  </policy_published>

  <record>
    <row>
      <source_ip>209.85.222.44</source_ip>
      <count>1</count>
      <policy_evaluated>
        <disposition>none</disposition>
        <dkim>pass</dkim>
        <spf>pass</spf>
      </policy_evaluated>
    </row>

    <identifiers>
      <header_from>sample.com</header_from>
    </identifiers>

    <auth_results>
      <dkim>
        <domain>sample.com</domain>
        <result>pass</result>
        <selector>google</selector>
      </dkim>
      <spf>
        <domain>sample.com</domain>
        <result>pass</result>
      </spf>
    </auth_results>
  </record>
</feedback>
Enter fullscreen mode Exit fullscreen mode

Conclusion

Although the initial use of MailApp was unintentional, as written at the beginning, this experience provided valuable knowledge about the best practice of using GmailApp and an understanding of email authentication technology. So, it was a good experience overall.

I hope to become a developer who can, in the future, intentionally propose MailApp as an option when the situation calls for it.

References

Top comments (0)