Site icon Mailtrap

How to Send Emails with SMTP from Popular Languages and Frameworks 

This is a featured image for an article on how to send emails with SMTP from popular languages and frameworks

In our blog posts, we regularly provide tutorials on sending emails from different programming languages and frameworks. SMTP server is almost always among the discussed methods. 

This time we’ve decided to unify all those resources and create a comprehensive guide on sending emails with SMTP. Below we’ll provide descriptions and code samples for PHP, Python, C#, Node.js, Java, and Ruby, as well as their corresponding frameworks. 

Email sending options: SMTP or Web API?

Generally, there are two main ways of sending emails: via SMTP server or Web API. 

An SMTP server is an app that transfers messages from a sender to the recipient’s inbound mail server. It operates using Simple Mail Transfer Protocol (or SMTP protocol) which defines the terms for sending emails. In that process, messages are moved between mail transfer agents (MTAs) that are often synonymous with SMTP relay servers. 

To transmit messages successfully, the SMTP client has to establish a connection with the email server (as per RFC 5321). They are like old pals who met up for a drink to catch up. But instead of sentences, they communicate through SMTP commands and responses (for example, HELO, MAIL FROM, RCPT TO, DATA, AUTH, etc.). The SMTP connection is carried out using Transmission Control Protocol (TCP) through SMTP ports: 25, 465, 587, and 2525. 

People usually opt for the SMTP server because: 

A Web API (application programming interface) makes it possible to integrate third-party services directly with your app or project. For emails, Web APIs are usually called Email APIs. They communicate with other services with HyperText Transfer Protocol (HTTP). In this case, the communication is more like a one-liner than a full-blown conversation. 

Email APIs enable users to send emails directly from their app by integrating email service providers (ESPs). 

Here’s why folks choose to use Email API: 

For more on the differences between Web API and SMTP server, check out our dedicated blog post

Before sending emails: choosing the SMTP server provider

You’ll need a reliable SMTP server provider to send high volumes of emails and maintain good email deliverability. To choose one, we recommend using the following criteria: 

The majority of SMTP providers offer free SMTP servers along with their paid plans. These come in the shape of free trials or free tiers. 

Most popular email providers include Mailgun, SendGrid, Mailchimp Transactional Email (former Mandrill), Postmark, Amazon SES, and Mailtrap

Mailtrap is an Email Delivery Platform for businesses, individuals, and developer teams that enables users to test, send, and control the performance of their infrastructure in one place. For that purpose, it combines two solutions: Email Testing (more on that later) and Email Sending

Email Sending is a robust email infrastructure designed with high deliverability rates by default. To ensure a smooth and secure setup, it has both Email API and SMTP service. 

Apart from sending capabilities, Email Sending comes with additional features such as actionable analytics. With its help, users get access to helicopter-view dashboards and drill-down reports for mailbox providers and categories. That way, it’s easy to troubleshoot unexpected sending issues if they do occur. 

To start using Mailtrap Email Sending, all you need to do is sign up and follow the in-app wizard to add and verify your domain. For detailed instructions, watch the video below or refer to our getting started guide

Next, head over to the Sending Domains, click on the verified domain and navigate to the ‘SMTP/API Settings’ tab. There, you’ll need to pick between a transactional and bulk stream and between using Mailtrap Email Sending’s SMTP service or email API.

In the API section, you’ll see ready-made snippets for different programming languages that you can insert directly into your project. 

In the SMTP tab, you’ll find the necessary credentials to easily integrate Mailtrap with SMTP. 

For the code snippets below, we’ll be using the SMTP credentials provided by Mailtrap Email Sending. 

Send emails with SMTP in PHP 

The easiest and most popular way to send emails with SMTP in PHP is through PHPMailer. It’s compatible with PHP 5.5 and higher. This package supports SMTP authentication, TLS and SSL security layers, validates email addresses automatically, and protects against header injection attacks. Unlike PHP’s native mail() function, PHPMailer doesn’t have inherent deliverability issues. 

To start using the package, you should install it via composer by adding the following code to your composer.json file: 

"phpmailer/phpmailer": "^6.8.0" 

Alternatively, you can just run composer require phpmailer/phpmailer and PHPMailer will be installed. 

After that, the first thing you need to do is import the PHPMailer classes in the global namespace. Then load the autoloader with the require statement. You also need to create an instance with the true parameter to enable the exceptions. 

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

Now it’s time to configure the SMTP server. For that, we need to go back to our Mailtrap Email Sending account and copy the SMTP credentials. We also have to configure the encryption protocol. In this case, let’s choose STARTTLS with port number 587. 

$mail->SMTPDebug = SMTP::DEBUG_SERVER;                    
$mail->isSMTP();                                      
$mail->Host       = 'live.smtp.mailtrap.io';                  
$mail->SMTPAuth   = true;                                
$mail->Username   = 'api';                    
$mail->Password   = 'YOUR_API_TOKEN';                         
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;          
$mail->Port       = 587;

Once the SMTP is configured, we can set the sender and recipient addresses, reply-to address, as well as carbon copy (Cc) and blind carbon copy (Bcc) addresses. 

$mail->setFrom('kate@mailtrap.io', 'Kate');
$mail->addAddress('noah@example.net', 'Joe User');   
$mail->addAddress('denys@example.com');             
$mail->addReplyTo('info@mailtrap.io', 'Information');
$mail->addCC('vika@example.com');
$mail->addBCC('oliver@example.com');

PHPMailer makes it possible to add attachments with addAttachment method and define the body of the email as HTML or plain text. 

$mail->addAttachment('/var/tmp/file.tar.gz');        
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); 

$mail->isHTML();                               
$mail->Subject = 'Mailtrap is awesome';
$mail->Body    = 'This is my first HTML email sent with Mailtrap <b>in bold!</b>';
$mail->AltBody = 'This is the plain text body if you’re using non-HTML email client';

The final step is to send the test message by calling the send method. 

try {
    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo $e->getMessage();
}

If you did everything correctly, you should receive an email in the selected inbox. After receiving the email, go back to the Mailtrap account and click ‘Verify Setup’ to start sending emails from your app. 

Note: We won’t replicate this step in the following sections. Remember that it’s essential to verify your setup, no matter which programming language or framework you’re using. 

For a more detailed tutorial and other examples, refer to our guide on sending emails with PHPMailer

Also, if you decide that sending via SMTP in PHP isn’t for you, make sure to check out the official Mailtrap PHP client.

Send emails with SMTP in Laravel

Laravel is a free, open-source, scalable PHP framework suitable for building complex applications. And along with other perks, it also allows you to send emails with SMTP, HTTP, or API. This is done with the help of Symfony Mailer

For today’s tutorial, we’ll assume that you already have a Laravel application up and running. Keep in mind that you should configure email services in config/mail.php and .env files. 

To get started with SMTP sending, you should add the following lines of code to your .env file: 

MAIL_DRIVER=smtp
MAIL_HOST=live.smtp.mailtrap.io
MAIL_PORT=587
MAIL_USERNAME=api
MAIL_PASSWORD=YOUR_API_TOKEN
MAIL_ENCRYPTION=tls

Note: Don’t forget to substitute MAIL_PASSWORD with the API token provided by Mailtrap. The username (api) is the same for every user. 

The next step is to create a new mailable class. In Laravel, mailable classes represent the types of emails you send. They are stored in the app/Mail directory. Creating a new mailable class is easy as it requires running a simple command: 

php artisan make:mail LaravelSMTPConfiguration

Within the mailable class, you can configure envelope, content, and attachment methods for deeper tweaks. The envelope is used for defining the subject and from address of the email. 

use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Envelope;

/**
* Get the message envelope.
*/
public function envelope(): Envelope
{
    return new Envelope(
        from: new Address('kate@mailtrap.io', 'Kate from Mailtrap'),
        subject: 'Laravel SMTP Configuration',
    );
}

The content enables you to define the view i.e. choose which template to use for the content. Usually, templates operate on the Blade engine. This is useful if you want to send HTML emails. Plain-text email messages should also be stored as a template in your blade.php file and called alongside the HTML (this step is optional but recommended). 

/**
* Get the message content definition.
*/
public function content(): Content
{
    return new Content(
        view: 'emails.smtp.configuration',
        text: 'emails.smtp.configuration-text'
    );
}

The final stage is to define the route in the routes/web.php file for sending the SMTP emails. For that, we need to import Mail facade and specify the recipient’s address. 

<?php

use Illuminate\Support\Facades\Route;
use App\Mail\LaravelSMTPConfiguration;
use Illuminate\Support\Facades\Mail;

Route::get('/testroute', function() {
    $name = "Kate from Mailtrap";

    //The email sending is done using the to method on the Mail facade
    Mail::to('noah@example.com'')->send(new LaravelSMTPConfiguration($name));
});

Another option is to add a CLI command to send emails. Using CLI without WEB is easier in some cases. 

use App\Mail\LaravelSMTPConfiguration;
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Mail;

/*
|--------------------------------------------------------------------------
| Console Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of your Closure based console
| commands. Each Closure is bound to a command instance allowing a
| simple approach to interacting with each command's IO methods.
|
*/

Artisan::command('inspire', function () {
    $this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');


Artisan::command('sendmail', function () {
    Mail::to('testreceiver@gmail.com')->send(
      new LaravelSMTPConfiguration("Kate from Mailtrap"));
})->purpose('Send test mail');

We’ve described this process in more detail in our dedicated tutorial on sending emails with Laravel. There, you’ll also find information on adding attachments and sending emails through an API. And on the Mailtrap bridge for Laravel framework [API] GitHub page, you can learn how to integrate this API into your app/project with ease.

If you’re using Symfony instead of Laravel, you’ll find all the necessary information here

Send emails with SMTP in Python

Python has a native library for sending emails with an SMTP server. smtplib can be used to define an SMTP client and, of course, route outgoing emails. To start using the library, you should use import smtplib statement and create the SMTP object with the following code: 

smtplib.SMTP(host='', port=0, local_hostname=None, [timeout, ]source_address=None)

We should also specify the sender, recipient, and the message itself. The final step is to send the email with SMTP.sendmail object. 

An example with Mailtrap’s credentials will look like this: 

import smtplib

sender = 'kate@mailtrap.io'
receivers = ['noah@example.com']
message = """From: Kate from Mailtrap <kate@mailtrap.io>
To: Noah Doe <noah@example.com>
Subject: Check out my awesome email


This is my first email sent with Python using Mailtrap's SMTP credentials. WDYT?
"""

try:
    smtpObj = smtplib.SMTP('live.smtp.mailtrap.io', 587)
    smtpObj.sendmail(sender, receivers, message)        
    print("Successfully sent email")
except SMTPException:
    pass

Official documentation recommends using the features of the email package to build email messages and add MIME attachments. You might also want to have a look at our send with Python blog post for step-by-step instructions. And while you’re at it, don’t forget to check out our official Python client for cases when SMTP isn’t the right option. 

Send emails with SMTP in Django 

As a Python framework, Django’s email sending functionalities are based on smtplib we discussed above. However, the main code pieces are stored in the django.core.mail module. 

Start by adding SMTP configuration to your settings.py file. Swap EMAIL_HOST variable with Mailtrap’s SMTP host and specify the port. Then go ahead and define the username and password of your host. Don’t forget to specify the encryption type (either EMAIL_USE_TLS or EMAIL_USE_SSL should be set to true). 

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'live.smtp.mailtrap.io'
EMAIL_PORT = '587'
EMAIL_HOST_USER = 'api'
EMAIL_HOST_PASSWORD = 'your_api_token'
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False

Let’s move on to sending emails. Begin the file by importing send_mail from django.core.mail file. 

from django.core.mail import send_mail 

Continue by specifying four necessary components: subject, message, from_email, and recipient_list

from django.core.mail import send_mail

send_mail(
    subject = 'My awesome email sent from Django'
    message = 'Look! I’ve enabled SMTP email sending in my Django app with Mailtrap. Isn’t that awesome?'
    from_email = 'kate@mailtrap.io'
    recipient_list = ['noah@example.com',]
    auth_user = 'Login'
    auth_password = 'Password'
    fail_silently = False,
)

To learn how to add multiple recipients, send mass emails, or define other parameters, read this blog post

Send emails with SMTP in C# and .NET

For many years, the default way of sending emails with SMTP in C# was through .NET framework and SmtpClient class. However, SmtpClient is now obsolete as it doesn’t correspond to modern security requirements and protocols. Microsoft itself recommends using MailKit or other libraries. 

For today’s tutorial, we’ll be using MailKit – a cross-platform .NET library. 

As with other frameworks and programming languages, the first step is installation. Go to the Package Manager Console in the Visual Studio and run the following command: 

Install-Package MailKit

Start the code by importing the necessary namespaces such as System, MailKit.Net.Smtp, MailKit, and MimeKit. Then create a new MimeMessage class to represent the email message. Typically, you’ll also have to configure the sender, recipient, subject, and body. To send emails, it’s important to create a new SmtpClient class (don’t confuse it with .NET’s SmtpClient we mentioned above). 

After specifying the SMTP server and port, you can send emails with send() method. This is what a sample code will look like after building the necessary components: 

using System;


using MailKit.Net.Smtp;
using MailKit;
using MimeKit;


namespace TestClient
{
   class Program
   {
       public static void Main (string[] args)
       {
           using var email = new MimeMessage();


           email.From.Add(new MailboxAddress("Kate from Mailtrap", "kate@mailtrap.io"));
           email.To.Add(new MailboxAddress("Noah", "Noah@example.com"));


           email.Subject = "Now I’m even sending emails from C#!";
           email.Body = new TextPart(MimeKit.Text.TextFormat.Html) {
               Text = "<b>Check out my C# SMTP email sent with MailKit and Mailtrap’s SMTP credentials</b>"
           };


           using var smtp = new SmtpClient();
           smtp.Connect("live.smtp.mailtrap.io", 587, false);


           // Note: only needed if the SMTP server requires authentication
           smtp.Authenticate("api", "your_api_token");


           smtp.Send(email);
           smtp.Disconnect(true);
       }
   }
}

MailKit can be used to send emails from ASP.NET C# and ASP.NET Core. You’ll find more methods of sending emails in C# here

Send emails with SMTP in Node.js 

Nodemailer is the most popular option for sending emails with SMTP in Node.js. Even though other packages are also available, Nodemailer seems to be dominating the scene with its simple yet robust code. If you’re interested in other packages and sending options, refer to our detailed tutorial

You can start sending emails in just a few steps: 

  1. Install the package with npm install nodemailer or yarn add nodemailer commands and import it using the following line of code: 
const nodemailer = require('nodemailer') 
  1. Create an SMTP transport. General options include host, port, auth, and authMethod. However, you can also specify TLS, connection, security, debug, and other options here. Here’s a sample code with general options: 
  const transporter = nodemailer.createTransport({
    host: 'live.smtp.mailtrap.io',
    port: 587,
    secure: false, // upgrade later with STARTTLS
    auth: {
      user: 'api',
      pass: 'your_api_token'
    }
  })
  1. Create an email message with the necessary parameters. Refer to the official documentation for more information on supported parameters. 
  const message = {
    from: 'kate@mailtrap.io',
    to: 'noah@example.com',
    subject: 'This time I\'m using Nodemailer',
    text: 'This is my first email sent with Nodemailer and Mailtrap. Does it look good?',
    html: '<p>This is my first email sent with Nodemailer and Mailtrap. Does it look good?</p>'
  }
  1. Send the email. 
  const info = await transporter.sendMail(message)
  console.log(`Email sent: ${info.response}`) 

We also have a step-by-step guide on Nodemailer here

Send emails with SMTP in Java 

Similar to other programming languages, you’ll need a separate package to send emails in Java using the SMTP server. Angus Mail (former JakartaMail and JavaMail) is usually the primary choice for Java developers. 

Note: The source codes of JakartaMail were moved to Eclipse Angus and the development continues there. Angus Mail is the successor of JakartaMail. 

You have two main options to get started:

  1. Download angus-mail.jar (JakartaMail implementation) and jakarta.mail-api.jar and add them to the class or module path of the Angus Activation. 
  2. Find angus-mail.jar in the Maven repository and add it to the Maven dependency: 
<dependencies>
    <dependency>
        <groupId>jakarta.mail</groupId>
        <artifactId>jakarta.mail-api</artifactId>
        <version>2.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.eclipse.angus</groupId>
        <artifactId>angus-mail</artifactId>
        <version>2.0.1</version>
        <scope>runtime</scope>
    </dependency>
</dependencies>

You can then start building your email by importing all the necessary parameters. public class JakartaEmail contains the main methods for sending emails and enables you to set to and from addresses and SMTP username and password. 

SMTP host, port and other SMTP parameters can be set using the properties object. The message subject and content can be created using MimeMessage object. 

To send the email, you’ll need to call Transport.send(message) method. 

package org.example.jakartaemail;
import java.util.Properties;
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;

public class JakartaEmail {
  public static void main(String[] args) {
      String to = "noah@example.com";
      String from = "kate@mailtrap.io";
      final String username = "api";      final String password = "your_api_token";
      String host = "live.smtp.mailtrap.io";
      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.host", host);
      props.put("mail.smtp.port", "587");
      //create the Session object
      Session session = Session.getInstance(props,
        new jakarta.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
              return new PasswordAuthentication(username, password);
    }
        });
      try {
    //create a MimeMessage object
    Message message = new MimeMessage(session);
    //set From email field
    message.setFrom(new InternetAddress(from));
    //set To email field
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
    //set email subject field
    message.setSubject("Here comes my SMTP email from Java!");
    //set the content of the email message
    message.setText("Just discovered that it’s easy to send emails with SMTP using JakartaMail and Mailtrap");
    //send the email message
    Transport.send(message);
    System.out.println("Email Message Sent Successfully");
      } catch (MessagingException e) {
        throw new RuntimeException(e);
      }
  }
}

Send emails with SMTP in Ruby/Ruby on Rails 

The last programming language and framework we have here are Ruby and Ruby on Rails, respectively. The preferred way of sending emails with SMTP for both of them is ActionMailer. For a Ruby-specific tutorial, check out this blog post

Install ActionMailer using RubyGems by adding this line of code: 

gem install actionmailer

Now we need to create a new mailer file in the app/mailers directory of the Ruby app. 

rails generate mailer User

Email messages can be built using various helpers that allow you to format messages or add attachments. A simple email will look something like this: 

class UserMailer < ApplicationMailer
  def simple_message(recipient)
    attachments["attachment.pdf"] = File.read("path/to/file.pdf")
    mail(
      to: recipient,
      subject: "I’ve even configured Ruby",
      content_type: "text/html",
      body: "<html><strong>I’m turning into a real SMTP pro</strong></html>"
    )
  end
end

Before sending the email, we need to edit config/environments/*.rb with the correct SMTP credentials like so: 

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  :address   => 'live.smtp.mailtrap.io',
  :port      => 587,
  :domain    => 'example.com',
  :user_name => 'api',
  :password  => 'your_api_token',
  :authentication => 'plain',
  :enable_starttls_auto => true
}

All that’s left is to call the deliver_now method on the return value. 

message = UserMailer.simple_message("noah@example.com") 
message.deliver_now 

More detailed configurations using ActionMailer are available in this guide

Sending limitations when using free SMTP server providers

While free SMTP servers are attractive because they are free, their providers usually limit sending significantly. This is particularly true for Gmail, Outlook, Yahoo!, and similar SMTP servers. Here’s a chart with the most popular email services and their limitations. 

Email serviceLimitations 
Gmail500 emails per day
Outlook300 emails per day 
Yahoo! N/A (doesn’t disclose exact numbers)
iCloud Mail1,000 emails per day
Zoho Mail 150 emails per day (50 per confirmed user)
AOLN/A (doesn’t disclose exact numbers)

Sending limitations aside, email accounts with free domain names (such as @gmail.com, @yahoo.com, etc.) don’t provide access to DNS records. In other words, you can’t implement authentication protocols that are essential for building and maintaining high email deliverability rates. 

Moreover, mass emails coming from such accounts are usually blocked or marked as spam by internet service providers (ISPs). 

That’s why it’s recommended to use paid SMTP services to route your outgoing mail. For personal use or to send occasional emails, you can, of course, opt for free SMTP servers. 

Send emails with Gmail SMTP

You can use Gmail SMTP with any of the methods we’ve described above. You’ll simply have to insert the credentials of Gmail’s SMTP server. However, keep in mind that you’ll need to sign in using app passwords. Learn how to create one here

To configure Gmail SMTP, you should use the following credentials: 

Send emails with Outlook or Microsoft 365 SMTP

Similar to Gmail SMTP, Outlook or Microsoft 365 SMTP server can be used to send emails from your app. These are the credentials you’ll need: 

Why should you test emails before sending and how?

When you’re configuring SMTP settings to send emails from your app, a lot can go wrong. Your HTML might not render properly. The personalization variables may be completely off. Or your emails may be skipping inboxes altogether. 

All of those can easily be avoided if you test emails before sending them to your users. A simple tool such as Mailtrap Email Testing will help you inspect and debug your emails in a safe environment. 

Test Your SMTP Configuration with Mailtrap for Free 

Email Testing catches all the SMTP traffic in a virtual inbox, leaving zero chances for spamming users. That way, you can easily test the email sending capabilities of your app in staging. 

Apart from that, Email Testing will help you inspect HTML/CSS to ensure it’s rendered correctly in different email clients. Faulty lines of code will be displayed right in your virtual inbox to easily correct/remove them. 

Email Testing also checks the spam score of your emails. By keeping the score below 5, you can prevent significant deliverability issues when your app moves to production. 

To test the SMTP in your app, you can integrate Email Testing with credentials for the fake SMTP server. Or you can take it a step further and integrate it using ready-made code snippets for more flexibility. 

Mailtrap is one platform that can cover all of your email-related needs. Use Email Testing to debug your app’s sending functionality in staging, send emails with SMTP using Email Sending, and monitor the performance of your infrastructure with actionable analytics. 

Exit mobile version