[email] How to send email using simple SMTP commands via Gmail?

For educational purposes, I need to send an email through an SMTP server, using SMTP's fundamental and simple rules.

I was able to do that using smtp4dev. I telnet localhost 25 and and commands are:

enter image description here

I want to do the same thing, using Gmail SMTP server. However, it requires authentication and TLS. I can't figure out how to do that for Gmail. Here's a screenshot of telnet smtp.gmail.com 587:

enter image description here

I searched and found many links including Wikipedia's article about STARTTLS command. But I'm not able to use TLS and authenticate to Gmail's SMTP server using command line (or sending commands myself in programming languages). Can anyone help?

This question is related to email smtp gmail smtpclient smtp-auth

The answer is


As no one has mentioned - I would suggest to use great tool for such purpose - swaks

# yum info swaks
Installed Packages
Name        : swaks
Arch        : noarch
Version     : 20130209.0
Release     : 3.el6
Size        : 287 k
Repo        : installed
From repo   : epel
Summary     : Command-line SMTP transaction tester
URL         : http://www.jetmore.org/john/code/swaks
License     : GPLv2+
Description : Swiss Army Knife SMTP: A command line SMTP tester. Swaks can test
            : various aspects of your SMTP server, including TLS and AUTH.

It has a lot of options and can do almost everything you want.

GMAIL: STARTTLS, SSLv3 (and yes, in 2016 gmail still support sslv3)

$ echo "Hello world" | swaks -4 --server smtp.gmail.com:587 --from [email protected] --to [email protected] -tls --tls-protocol sslv3 --auth PLAIN --auth-user [email protected] --auth-password 7654321 --h-Subject "Test message" --body -
=== Trying smtp.gmail.com:587...
=== Connected to smtp.gmail.com.
<-  220 smtp.gmail.com ESMTP h8sm76342lbd.48 - gsmtp
 -> EHLO www.example.net
<-  250-smtp.gmail.com at your service, [193.243.156.26]
<-  250-SIZE 35882577
<-  250-8BITMIME
<-  250-STARTTLS
<-  250-ENHANCEDSTATUSCODES
<-  250-PIPELINING
<-  250-CHUNKING
<-  250 SMTPUTF8
 -> STARTTLS
<-  220 2.0.0 Ready to start TLS
=== TLS started with cipher SSLv3:RC4-SHA:128
=== TLS no local certificate set
=== TLS peer DN="/C=US/ST=California/L=Mountain View/O=Google Inc/CN=smtp.gmail.com"
 ~> EHLO www.example.net
<~  250-smtp.gmail.com at your service, [193.243.156.26]
<~  250-SIZE 35882577
<~  250-8BITMIME
<~  250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
<~  250-ENHANCEDSTATUSCODES
<~  250-PIPELINING
<~  250-CHUNKING
<~  250 SMTPUTF8
 ~> AUTH PLAIN AGFhQxsZXguaGhMGdATGV4X2hoYtYWlsLmNvbQBS9TU1MjQ=
<~  235 2.7.0 Accepted
 ~> MAIL FROM:<[email protected]>
<~  250 2.1.0 OK h8sm76342lbd.48 - gsmtp
 ~> RCPT TO:<[email protected]>
<~  250 2.1.5 OK h8sm76342lbd.48 - gsmtp
 ~> DATA
<~  354  Go ahead h8sm76342lbd.48 - gsmtp
 ~> Date: Wed, 17 Feb 2016 09:49:03 +0000
 ~> To: [email protected]
 ~> From: [email protected]
 ~> Subject: Test message
 ~> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
 ~>
 ~> Hello world
 ~>
 ~>
 ~> .
<~  250 2.0.0 OK 1455702544 h8sm76342lbd.48 - gsmtp
 ~> QUIT
<~  221 2.0.0 closing connection h8sm76342lbd.48 - gsmtp
=== Connection closed with remote host.

YAHOO: TLS aka SMTPS, tlsv1.2

$ echo "Hello world" | swaks -4 --server smtp.mail.yahoo.com:465 --from [email protected] --to [email protected] --tlsc --tls-protocol tlsv1_2 --auth PLAIN --auth-user [email protected] --auth-password 7654321 --h-Subject "Test message" --body -
=== Trying smtp.mail.yahoo.com:465...
=== Connected to smtp.mail.yahoo.com.
=== TLS started with cipher TLSv1.2:ECDHE-RSA-AES128-GCM-SHA256:128
=== TLS no local certificate set
=== TLS peer DN="/C=US/ST=California/L=Sunnyvale/O=Yahoo Inc./OU=Information Technology/CN=smtp.mail.yahoo.com"
<~  220 smtp.mail.yahoo.com ESMTP ready
 ~> EHLO www.example.net
<~  250-smtp.mail.yahoo.com
<~  250-PIPELINING
<~  250-SIZE 41697280
<~  250-8 BITMIME
<~  250 AUTH PLAIN LOGIN XOAUTH2 XYMCOOKIE
 ~> AUTH PLAIN AGFhQxsZXguaGhMGdATGV4X2hoYtYWlsLmNvbQBS9TU1MjQ=
<~  235 2.0.0 OK
 ~> MAIL FROM:<[email protected]>
<~  250 OK , completed
 ~> RCPT TO:<[email protected]>
<~  250 OK , completed
 ~> DATA
<~  354 Start Mail. End with CRLF.CRLF
 ~> Date: Wed, 17 Feb 2016 10:08:28 +0000
 ~> To: [email protected]
 ~> From: [email protected]
 ~> Subject: Test message
 ~> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
 ~>
 ~> Hello world
 ~>
 ~>
 ~> .
<~  250 OK , completed
 ~> QUIT
<~  221 Service Closing transmission
=== Connection closed with remote host.

I have been using swaks to send email notifications from nagios via gmail for last 5 years without any problem.


Unfortunately as I am forced to use a windows server I have been unable to get openssl working in the way the above answer suggests.

However I was able to get a similar program called stunnel (which can be downloaded from here) to work. I got the idea from www.tech-and-dev.com but I had to change the instructions slightly. Here is what I did:

  1. Install telnet client on the windows box.
  2. Download stunnel. (I downloaded and installed a file called stunnel-4.56-installer.exe).
  3. Once installed you then needed to locate the stunnel.conf config file, which in my case I installed to C:\Program Files (x86)\stunnel
  4. Then, you need to open this file in a text viewer such as notepad. Look for [gmail-smtp] and remove the semicolon on the client line below (in the stunnel.conf file, every line that starts with a semicolon is a comment). You should end up with something like:

    [gmail-smtp]
    client = yes
    accept = 127.0.0.1:25
    connect = smtp.gmail.com:465
    

    Once you have done this save the stunnel.conf file and reload the config (to do this use the stunnel GUI program, and click on configuration=>Reload).

Now you should be ready to send email in the windows telnet client!
Go to Start=>run=>cmd.

Once cmd is open type in the following and press Enter:

telnet localhost 25

You should then see something similar to the following:

220 mx.google.com ESMTP f14sm1400408wbe.2

You will then need to reply by typing the following and pressing enter:

helo google

This should give you the following response:

250 mx.google.com at your service

If you get this you then need to type the following and press enter:

ehlo google

This should then give you the following response:

250-mx.google.com at your service, [212.28.228.49]
250-SIZE 35651584
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH
250 ENHANCEDSTATUSCODES

Now you should be ready to authenticate with your Gmail details. To do this type the following and press enter:

AUTH LOGIN

This should then give you the following response:

334 VXNlcm5hbWU6

This means that we are ready to authenticate by using our gmail address and password.

However since this is an encrypted session, we're going to have to send the email and password encoded in base64. To encode your email and password, you can use a converter program or an online website to encode it (for example base64 or search on google for ’base64 online encoding’). I reccomend you do not touch the cmd/telnet session again until you have done this.

For example [email protected] would become dGVzdEBnbWFpbC5jb20= and password would become cGFzc3dvcmQ=

Once you have done this copy and paste your converted base64 username into the cmd/telnet session and press enter. This should give you following response:

334 UGFzc3dvcmQ6

Now copy and paste your converted base64 password into the cmd/telnet session and press enter. This should give you following response if both login credentials are correct:

235 2.7.0 Accepted

You should now enter the sender email (should be the same as the username) in the following format and press enter:

MAIL FROM:<[email protected]>

This should give you the following response:

250 2.1.0 OK x23sm1104292weq.10

You can now enter the recipient email address in a similar format and press enter:

RCPT TO:<[email protected]>

This should give you the following response:

250 2.1.5 OK x23sm1104292weq.10

Now you will need to type the following and press enter:

DATA

Which should give you the following response:

354  Go ahead x23sm1104292weq.10

Now we can start to compose the message! To do this enter your message in the following format (Tip: do this in notepad and copy the entire message into the cmd/telnet session):

From: Test <[email protected]>
To: Me <[email protected]>
Subject: Testing email from telnet
This is the body

Adding more lines to the body message.

When you have finished the email enter a dot:

.

This should give you the following response:

250 2.0.0 OK 1288307376 x23sm1104292weq.10

And now you need to end your session by typing the following and pressing enter:

QUIT

This should give you the following response:

221 2.0.0 closing connection x23sm1104292weq.10
Connection to host lost.

And your email should now be in the recipient’s mailbox!


Based on the existing answers, here's a step-by-step guide to sending automated e-mails over SMTP, using a GMail account, from the command line, without disclosing the password.

Requirements

First, install the following software packages:

These instructions assume a Linux operating system, but should be reasonably easy to port to Windows (via Cygwin or native equivalents), or other operating system.

Authentication

Save the following shell script as authentication.sh:

#!/bin/bash

# Asks for a username and password, then spits out the encoded value for
# use with authentication against SMTP servers.

echo -n "Email (shown): "
read email
echo -n "Password (hidden): "
read -s password
echo

TEXT="\0$email\0$password"

echo -ne $TEXT | base64

Make it executable and run it as follows:

chmod +x authentication.sh
./authentication.sh

When prompted, provide your e-mail address and password. This will look something like:

Email (shown): [email protected]
Password (hidden): 
AGJvYkBnbWFpbC5jb20AYm9iaXN0aGViZXN0cGVyc29uZXZlcg==

Copy the last line (AGJ...==), as this will be used for authentication.

Notification

Save the following expect script as notify.sh (note the first line refers to the expect program):

#!/usr/bin/expect

set address "[lindex $argv 0]"
set subject "[lindex $argv 1]"
set ts_date "[lindex $argv 2]"
set ts_time "[lindex $argv 3]"

set timeout 10
spawn openssl s_client -connect smtp.gmail.com:465 -crlf -ign_eof 

expect "220" {
  send "EHLO localhost\n"

  expect "250" {
    send "AUTH PLAIN YOUR_AUTHENTICATION_CODE\n"

    expect "235" {
      send "MAIL FROM: <YOUR_EMAIL_ADDRESS>\n"

      expect "250" {
        send "RCPT TO: <$address>\n"

        expect "250" {
          send "DATA\n"

          expect "354" {
            send "Subject: $subject\n\n"
            send "Email sent on $ts_date at $ts_time.\n"
            send "\n.\n"

            expect "250" {
                send "quit\n"
            }
          }
        }
      }
    }
  }
}

Make the following changes:

  1. Paste over YOUR_AUTHENTICATION_CODE with the authentication code generated by the authentication script.
  2. Change YOUR_EMAIL_ADDRESS with the e-mail address used to generate the authentication code.
  3. Save the file.

For example (note the angle brackets are retained for the e-mail address):

send "AUTH PLAIN AGJvYkBnbWFpbC5jb20AYm9iaXN0aGViZXN0cGVyc29uZXZlcg==\n"
send "MAIL FROM: <[email protected]>\n"

Lastly, make the notify script executable as follows:

chmod +x notify.sh

Send E-mail

Send an e-mail from the command line as follows:

./notify.sh [email protected] "Command Line" "March 14" "15:52"

Examples related to email

Monitoring the Full Disclosure mailinglist require(vendor/autoload.php): failed to open stream Failed to authenticate on SMTP server error using gmail Expected response code 220 but got code "", with message "" in Laravel How to to send mail using gmail in Laravel? Laravel Mail::send() sending to multiple to or bcc addresses Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate How to validate an e-mail address in swift? PHP mail function doesn't complete sending of e-mail How to validate email id in angularJs using ng-pattern

Examples related to smtp

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error PHPMailer - SMTP ERROR: Password command failed when send mail from my server php function mail() isn't working Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required "An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14" SmtpException: Unable to read data from the transport connection: net_io_connectionclosed How to configure SMTP settings in web.config Send mail via CMD console Mail not sending with PHPMailer over SSL using SMTP

Examples related to gmail

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted How to to send mail using gmail in Laravel? HTML image not showing in Gmail Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required Send email from localhost running XAMMP in PHP using GMAIL mail server The server response was: 5.7.0 Must issue a STARTTLS command first. i16sm1806350pag.18 - gsmtp Gmail: 530 5.5.1 Authentication Required. Learn more at Sending mail attachment using Java Javamail Could not convert socket to TLS GMail Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

Examples related to smtpclient

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error How to send email using simple SMTP commands via Gmail? Why do I get "'property cannot be assigned" when sending an SMTP email? How to set username and password for SmtpClient object in .NET? smtpclient " failure sending mail"

Examples related to smtp-auth

Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14" Gmail: 530 5.5.1 Authentication Required. Learn more at Login credentials not working with Gmail SMTP How to send email using simple SMTP commands via Gmail? Sending emails through SMTP with PHPMailer How to resolve javax.mail.AuthenticationFailedException issue?