Sending emails programmatically is a common requirement for many applications — from registration confirmations and password resets to automated notifications. Gmail’s SMTP server is a popular choice because of its reliability and strong security features.
However, since Google disabled “Less Secure Apps,” you can no longer authenticate with your regular Gmail password. If your account has 2-Step Verification enabled, you must use an App Password instead.
In this guide, you’ll learn how to send emails securely through Gmail SMTP using App Passwords, with practical code examples in C#, JavaScript (Node.js), PHP, and Java.
Why Use Gmail App Passwords?
Google no longer allows SMTP authentication using your main Gmail password when 2-Step Verification is enabled. Instead, you can generate a unique 16-character App Password specifically for your application.
This approach enhances security by:
-
Preventing exposure of your main Gmail password
-
Restricting access to only the intended app
-
Allowing easy revocation of the App Password without affecting your main account
How to Generate a Gmail App Password
-
Sign in to your Google Account: https://myaccount.google.com
-
Go to Security → Signing in to Google
-
Enable 2-Step Verification if it’s not already enabled
-
Click on App Passwords
-
Select Mail as the app and choose your device or “Other (Custom name)” as the platform
-
Click Generate and copy the 16-character App Password shown
Use this App Password instead of your Gmail password in your SMTP client.
Sending Email Examples
C# Example
using System;
using System.Net;
using System.Net.Mail;
class Program
{
static void Main()
{
var smtpClient = new SmtpClient("smtp.gmail.com", 587)
{
EnableSsl = true,
Credentials = new NetworkCredential("your_email@gmail.com", "your_app_password")
};
var mail = new MailMessage
{
From = new MailAddress("your_email@gmail.com", "No-Reply"),
Subject = "Test Email from C# App",
Body = "This is a test message sent from a C# console application."
};
mail.To.Add("recipient@example.com");
try
{
smtpClient.Send(mail);
Console.WriteLine("Email sent successfully.");
}
catch (Exception ex)
{
Console.WriteLine("Error sending email: " + ex.Message);
}
}
}
Node.js Example (with Nodemailer)
const nodemailer = require('nodemailer');
async function sendEmail() {
let transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 587,
secure: false, // use TLS
auth: {
user: "your_email@gmail.com",
pass: "your_app_password",
},
});
let info = await transporter.sendMail({
from: '"No-Reply" <your_email@gmail.com>',
to: "recipient@example.com",
subject: "Test Email from Node.js",
text: "This is a test email sent from Node.js using Gmail SMTP.",
});
console.log("Message sent: %s", info.messageId);
}
sendEmail().catch(console.error);
PHP Example (with PHPMailer)
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_email@gmail.com';
$mail->Password = 'your_app_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('your_email@gmail.com', 'No-Reply');
$mail->addAddress('recipient@example.com');
$mail->Subject = 'Test Email from PHP';
$mail->Body = 'This is a test email sent from PHP using PHPMailer and Gmail SMTP.';
$mail->send();
echo 'Email sent successfully';
} catch (Exception $e) {
echo "Error sending email: {$mail->ErrorInfo}";
}
?>
Java Example (using JavaMail API)
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class GmailSMTPExample {
public static void main(String[] args) {
final String username = "your_email@gmail.com";
final String appPassword = "your_app_password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, appPassword);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your_email@gmail.com", "No-Reply"));
message.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse("recipient@example.com")
);
message.setSubject("Test Email from Java");
message.setText("This is a test email sent from Java using Gmail SMTP.");
Transport.send(message);
System.out.println("Email sent successfully");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Troubleshooting & Tips
-
Use port 587 for TLS or 465 for SSL
-
Use your App Password, not your Gmail password
-
Ensure your network/firewall allows outbound connections to
smtp.gmail.com
-
If you get “Username and Password not accepted,” verify 2-Step Verification and App Password settings
-
For high-volume or transactional emails, consider dedicated services like SendGrid, Mailgun, or Amazon SES
Sending emails securely with Gmail’s SMTP server using App Passwords is both simple and safe. Regardless of your development stack — C#, Node.js, PHP, or Java — the process follows the same pattern:
-
Generate a Gmail App Password
-
Configure your SMTP client with Gmail’s server and credentials
-
Compose and send your message
This setup ensures reliable delivery and keeps your Google account protected.