Thursday, March 3, 2011

Using gmail as a SMTP server

SMTP Server:
Use Authentication: Yes
Use Secure Connection: Yes (this can be TLS or SSL depending on your mail client)
Username: your GMail account
Password: your GMail password
Port: 465 or 587

(see from which I have copied this info)

Remember to add activation.jar and mail.jar to your CP.

If you get

try instead

if you are behind a Proxy; you are screwed

see also here for more on JavaMail API

and here for a working example.

Create an account in gmail, say "" with password "hello"

This code should definitely work - unless you are behind a proxy:


import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

 * A simple email sender class.
public class SimpleSender
     * Main method to send a message given on the command line.
    public static void main(String args[])
            String to="";
            String from="";
            String subject="fanculo";
            String body="sei scemissimo";
            send(to, from, subject, body);
        catch (Exception ex)
            System.out.println("Usage: java"
                    + "toAddress fromAddress subjectText bodyText");

     * "send" method to send the message.
    public static void send(String to, String from
            , String subject, String body)
     String smtpServer = ""; // or
        String username = "";
        String password = "hello";
            Properties props = System.getProperties();
            // -- Attaching to default Session, or we could start a new one --
            props.put("", smtpServer); 
            props.put("mail.smtp.port", "587"); // 587 465
   props.put("mail.smtp.user", username);
   props.put("mail.smtp.password", password);
            props.put("mail.smtp.auth", "true");           
            Session session = Session.getDefaultInstance(props, null);
            // -- Create a new message --
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
            // -- Set some other header information --
            message.setHeader("X-Mailer", "ThisIsPierre");
            message.setSentDate(new Date());
            // -- Send the message --
            Transport transport = session.getTransport("smtp");
            transport.connect(smtpServer, username, password);
            transport.sendMessage(message, message.getAllRecipients());
            System.out.println("Message sent OK.");
        catch (Exception ex)

Download JavaMail here

No comments: