How to Use Gmail as an SMTP Relay Service
Why Use Gmail as an SMTP Relay
Every app needs to send email. Password resets, order confirmations, contact form notifications, and those cron job alerts that tell you a backup finished. The default answer is to sign up with a transactional email provider, but for a side project or a single VPS, that is one more account, one more API key, and one more bill to babysit.
If you already own a Google account, Gmail can act as your outbound SMTP server. You get Google's deliverability, TLS encryption, and a login you already know. For low-volume sending (a few hundred messages a day), it is one of the fastest ways to get mail flowing without touching a credit card.
I have wired Gmail SMTP into more projects than I can count, from a WordPress site to a Raspberry Pi that emails me when a backup finishes. In this guide, I will show you how to enable it, the exact settings you need, the code for the most common stacks, and the limits that will bite you if you ignore them.
First, Let's Get the Terms Right
People say "Gmail as an SMTP relay" to describe two different things, and the setup is not the same for each.
smtp.gmail.com is the standard Gmail SMTP server. You authenticate with your Google account (or an app password) and send mail as that mailbox. This works for personal Gmail and Google Workspace accounts, and it is the right choice for most people.
smtp-relay.gmail.com is the dedicated Google Workspace SMTP relay service. It is built for on-premise servers, printers, scanners, and applications that need to send automated mail. It authenticates by IP address instead of a password, so devices that cannot do modern authentication can still send. You need a paid Google Workspace account for this one.
This article covers both, but let's start with the one you probably want.
Before You Start: Turn On 2-Step Verification
Google killed "less secure app" access. You can no longer log in to SMTP with your normal Gmail password. Your options are OAuth 2.0 or an app password. The app password is the pragmatic one, and it requires 2-Step Verification.
Here is how to create one:
Open your Google Account.
Go to Security and turn on 2-Step Verification if it is not active yet.
Back in Security, open 2-Step Verification and scroll down to App passwords.
Type a name such as "VPS uptime alerts" and click Create.
Copy the 16-character password Google shows you. It appears only once.
Treat the app password like a database password. Store it in a secrets manager or an environment variable, never in your code. If it leaks, revoke it from the same App passwords screen.
The Gmail SMTP Settings You Need
Setting | Value |
|---|---|
Server | `smtp.gmail.com` |
Port (SSL) | `465` |
Port (TLS / STARTTLS) | `587` |
Username | your full address, for example `[email protected]` |
Password | the app password from the step above |
Authentication | required |
Use port 465 with SSL or port 587 with STARTTLS. Avoid port 25: most providers and cloud hosts block it to fight spam anyway.
Method 1: Send With an App Password
This is the setup that works everywhere, from a laptop to a container. Here are the most common stacks.
Python
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg["Subject"] = "Backup finished"
msg["From"] = "[email protected]"
msg["To"] = "[email protected]"
msg.set_content("The nightly backup completed in 42 seconds.")
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:
smtp.login("[email protected]", "your16charapppw")
smtp.send_message(msg)
Node.js with Nodemailer
npm install nodemailer
import nodemailer from "nodemailer";
const transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true, // false when you use port 587
auth: {
user: process.env.GMAIL_USER,
pass: process.env.GMAIL_APP_PASSWORD,
},
});
await transporter.sendMail({
from: '"My App" <[email protected]>',
to: "[email protected]",
subject: "Hello from Gmail",
text: "Sent through Gmail SMTP.",
});
PHP with PHPMailer
<?php
use PHPMailer\PHPMailer\PHPMailer;
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Port = 587;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Username = '[email protected]';
$mail->Password = getenv('GMAIL_APP_PASSWORD');
$mail->setFrom('[email protected]', 'My App');
$mail->addAddress('[email protected]');
$mail->Subject = 'Hello from Gmail';
$mail->Body = 'Sent through Gmail SMTP.';
$mail->send();
Linux servers: msmtp and Postfix
For a whole server, msmtp is the lightest option. Add this to ~/.msmtprc (or /etc/msmtprc) and set the file permissions to 600:
account gmail
host smtp.gmail.com
port 587
auth on
user [email protected]
password your16charapppw
tls on
tls_starttls on
from [email protected]
account default : gmail
If you already run Postfix, point it at Gmail as a relay instead. In /etc/postfix/main.cf:
relayhost = [smtp.gmail.com]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_tls_security_level = encrypt
Create /etc/postfix/sasl_passwd with one line:
[smtp.gmail.com]:587 [email protected]:your16charapppw
Then hash it and reload:
sudo postmap /etc/postfix/sasl_passwd
sudo chmod 600 /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db
sudo systemctl reload postfix
Method 2: The Google Workspace SMTP Relay Service
If you run on-premise hardware (an old printer, a monitoring box, a legacy app) that cannot do OAuth or store an app password, the Google Workspace SMTP relay service is the answer. It authenticates by IP address, so a device on your network can send mail without a password.
Enable it in the Google Admin console:
Sign in to admin.google.com.
Go to Apps > Google Workspace > Gmail > Routing.
Find SMTP relay service and click Configure.
Add the Allowed senders (only addresses in your domains, or any address) and the Allowed IPs of your devices.
Save. It takes a few minutes to propagate.
Then point your device or mail server at smtp-relay.gmail.com:
relayhost = [smtp-relay.gmail.com]:587
Two rules to remember:
With TLS, use port 587. Without TLS you can use 25, 465, or 587, but then you must authenticate by IP only.
Never use this relay for mail that already originated from Gmail. Google calls this a mail loop risk and gives it "best effort" support only.
Method 3: OAuth 2.0 (When App Passwords Are Not Allowed)
Google now recommends OAuth 2.0 over app passwords, and some Workspace admins disable app passwords entirely. OAuth uses short-lived access tokens and refresh tokens instead of a static password, which is safer but more code. Nodemailer supports it directly:
const transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true,
auth: {
type: "OAuth2",
user: "[email protected]",
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
refreshToken: process.env.GOOGLE_REFRESH_TOKEN,
},
});
OAuth shines in multi-tenant apps, where each user grants your app permission to send on their behalf. For a personal project, an app password is far less work.
The Limits You Cannot Ignore
This is where most people get surprised. Gmail is a personal mailbox, not a bulk sender, and Google enforces that with quotas. All of these are counted over a rolling 24-hour window, not a calendar day.
Personal Gmail (@gmail.com):
About 500 recipients per day.
Around 100 to 500 recipients per message, depending on how you send.
Google Workspace via smtp.gmail.com:
2,000 messages per day per user.
Up to 10,000 total recipients per day and 3,000 external recipients per day.
Maximum attachment size around 25 MB per message.
Google Workspace SMTP relay service:
10,000 messages per 24 hours per user.
100 recipients per SMTP transaction. Exceed it and you must open a new connection.
Trial accounts get much lower limits until you pay a bill.
Exceed a limit and Google temporarily blocks sending from that account. For a hobby project it never comes up, but a runaway loop that retries failed emails can eat a daily quota in minutes. Add backoff and a queue, and you will be fine.
Test Your Setup Before You Trust It
Never assume SMTP works. Send a real message to a real inbox you control.
The fastest check from a terminal is swaks:
swaks --to [email protected] \
--server smtp.gmail.com:587 \
--auth LOGIN \
--auth-user [email protected] \
--auth-password "$GMAIL_APP_PASSWORD" \
--tls
If you prefer a browser, the GMass SMTP test fills in the same fields and tells you whether authentication and delivery succeed. Whichever tool you use, check the receiving inbox for the message and confirm it did not land in spam.
Common Errors and What They Mean
"Username and password not accepted" You used your normal Gmail password, not an app password. Turn on 2-Step Verification and create one.
"534-5.7.9 Application-specific password required" Same cause. Google will not accept the account password over SMTP.
"550 5.7.1 blocked" You sent too much, too fast, or your From address does not match the authenticated user.
"Daily user sending limit exceeded" You hit the quota. Queue the message and retry later, or move to a transactional provider.
TLS handshake errors on port 587 You enabled implicit SSL on the STARTTLS port. Use secure: false (Nodemailer) or ENCRYPTION_STARTTLS (PHPMailer) on 587.
The From address is rewritten Gmail always sends as the authenticated account. You cannot spoof a different sender without Workspace aliases.
When to Move to a Real Transactional Provider
Gmail SMTP is great until it is not. It sends as your @gmail.com address, so mail "from" your own domain will often fail SPF, DKIM, and DMARC alignment and land in spam. That alone rules it out for customer-facing transactional mail.
Reach for a provider such as Postmark, Mailgun, Amazon SES, or Resend when you need:
High volume or bulk or marketing sends.
Mail that sends as your own domain with proper DKIM signing.
Bounce handling, delivery analytics, and dedicated IPs.
A service level agreement you can point to when email breaks at 3 AM.
For internal alerts, a personal project, or a prototype, Gmail SMTP is more than enough. Use it to move fast, then swap it out when the product grows.
Key Takeaways
Use smtp.gmail.com for apps and smtp-relay.gmail.com for on-premise devices. They solve different problems.
Turn on 2-Step Verification and create an app password. Your normal Gmail password will not work over SMTP anymore.
Pick port 465 for SSL or 587 for STARTTLS, and never rely on port 25.
Respect the quotas. Roughly 500 recipients a day for personal Gmail, 2,000 messages for Workspace, and 10,000 for the relay. All rolling 24-hour windows.
Test with swaks before you ship. A silent auth failure is worse than a loud one.
Know when to leave. The moment you send as your own domain or need delivery analytics, switch to a transactional provider.
Gmail is the Swiss Army knife of email. It will not replace a dedicated sending service, but for the first version of almost anything, it gets the job done in minutes.
About the Author
Rogerio is a seasoned Full-Stack Engineer, Product Owner, and Entrepreneur with a deep background in Information Systems. He bridges the gap between complex technical stacks and a customer-centric, product-first mindset.