Send Email via SMTP: PHP, Node.js and Python Examples

Short, working examples for the most common languages and libraries. Each one uses port 587 with STARTTLS, with notes on what to change for port 465.

6 min read Updated 18 November 2026

Before you start

  • Get the SMTP host, port and credentials from your provider. The settings directory lists them for common providers.
  • Check the credentials with the SMTP test first, so a code bug and a settings problem don’t look the same.
  • Keep the password out of your code. The examples read it from an environment variable called SMTP_PASSWORD.

PHP with PHPMailer

Install with composer require phpmailer/phpmailer.

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host       = 'smtp.example.com';
    $mail->Port       = 587;
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;   // ENCRYPTION_SMTPS for port 465
    $mail->SMTPAuth   = true;
    $mail->Username   = '[email protected]';
    $mail->Password   = getenv('SMTP_PASSWORD');

    $mail->setFrom('[email protected]', 'Your Name');
    $mail->addAddress('[email protected]');
    $mail->Subject = 'Test from PHPMailer';
    $mail->Body    = 'It works.';

    $mail->send();
} catch (Exception $e) {
    echo 'Send failed: ' . $mail->ErrorInfo;
}

To see the full SMTP conversation while debugging, add $mail->SMTPDebug = 2;.

Node.js with Nodemailer

Install with npm install nodemailer.

const nodemailer = require('nodemailer');

const transporter = nodemailer.createTransport({
  host: 'smtp.example.com',
  port: 587,
  secure: false,            // true for port 465
  auth: {
    user: '[email protected]',
    pass: process.env.SMTP_PASSWORD,
  },
});

async function main() {
  await transporter.verify();   // checks connection and login
  const info = await transporter.sendMail({
    from: '"Your Name" <[email protected]>',
    to: '[email protected]',
    subject: 'Test from Nodemailer',
    text: 'It works.',
  });
  console.log('Sent:', info.messageId);
}

main().catch(console.error);

With secure: false Nodemailer upgrades to TLS with STARTTLS automatically when the server offers it.

Python with smtplib

No install needed: smtplib is in the standard library.

import os
import smtplib
from email.message import EmailMessage

msg = EmailMessage()
msg["From"] = "[email protected]"
msg["To"] = "[email protected]"
msg["Subject"] = "Test from Python"
msg.set_content("It works.")

with smtplib.SMTP("smtp.example.com", 587, timeout=20) as server:
    server.starttls()
    server.login("[email protected]", os.environ["SMTP_PASSWORD"])
    server.send_message(msg)

For port 465, use smtplib.SMTP_SSL("smtp.example.com", 465) and remove the starttls() line. Add server.set_debuglevel(1) to print the conversation.

Django settings

# settings.py
import os

EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.example.com"
EMAIL_PORT = 587
EMAIL_USE_TLS = True          # for port 465 use EMAIL_USE_SSL = True instead
EMAIL_HOST_USER = "[email protected]"
EMAIL_HOST_PASSWORD = os.environ["SMTP_PASSWORD"]
DEFAULT_FROM_EMAIL = "[email protected]"

Then send with django.core.mail.send_mail(subject, message, None, ["[email protected]"]). Set only one of EMAIL_USE_TLS and EMAIL_USE_SSL.

Common errors in code

  • Timeout or connection refused: the port is blocked where the code runs. Cloud servers usually block port 25; use 587 or 465.
  • wrong version number / SSL: WRONG_VERSION_NUMBER: SSL was used on a STARTTLS port. Use STARTTLS on 587, SSL only on 465.
  • 535 Authentication failed: wrong credentials or an app password is needed.
  • 550 sender rejected: the From address must match the login or a verified sender.

The SMTP error code reference explains other replies.

Frequently asked questions

Either works. Use 587 with STARTTLS unless your provider recommends 465. The only thing that matters is matching the encryption setting to the port.

Turn on the library’s debug output to see the server’s replies: SMTPDebug = 2 in PHPMailer, logger: true, debug: true in Nodemailer, set_debuglevel(1) in Python. Compare it with the transcript from our SMTP test.

No. Read it from an environment variable or a secrets manager, and use an app password or an API key that you can revoke if it leaks.