0 Replies - 2520 Views - Last Post: 19 January 2012 - 10:00 PM

#1 Dworza   User is offline

  • D.I.C Head
  • member icon

Reputation: 6
  • View blog
  • Posts: 172
  • Joined: 13-February 11

Sending email via gmail smtp

Posted 19 January 2012 - 10:00 PM

Description: At first you'll need to have some gmail account, because authorization from gmail smtp server is required. Implementation should be easy - main(String[] args) is included, so you can use it as a single project. There is a class called SMTPAuthenticator, which is used only for easier work with data for authorization. You'll also probably have to include javax.jar into your project.This is a class that allows you to send email with attachment via gmail smtp servers.
package net.dreamincode.emailsample

import java.util.Date;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;

public class SimpleMail {

    private static final String SMTP_HOST_NAME = "smtp.gmail.com"; // set the smtp server
    private static final String SMTP_AUTH_USER = "gmailUserName"; // fill in your gmail account user name
    private static final String SMTP_AUTH_PWD = "gmailUserPassword"; // fill in your gmail account password

    public static void main(String[] args) throws Exception {
        new SimpleMail().sendMail();
    }

    public void sendMail() throws Exception {

        //
        // Set the informations about transfer
        //
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");

        Authenticator auth = new SMTPAuthenticator();
        Session session = Session.getDefaultInstance(props, auth);
        Transport transport = session.getTransport();

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("[email protected]")); //displaied sender
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); //recepient
        message.setSubject("Some subject"); //subject of your email
        message.setSentDate(new Date()); //date, when was the email sent
      
        MimeBodyPart messagePart = new MimeBodyPart();
        messagePart.setText("Some text displaied in the body of your email");

        //
        // Set the email attachment file
        //
        MimeBodyPart attachmentPart = new MimeBodyPart();
        // tries to find file named "newimage.jpg"
        // when there is no such file, the programm crashes..you should better handle this with some condition
        FileDataSource fileDataSource = new FileDataSource("newimage.jpg") {
            @Override
            public String getContentType() {
                return "application/octet-stream";
            }
        };
        
        attachmentPart.setDataHandler(new DataHandler(fileDataSource));
        attachmentPart.setFileName("newimage.jpg"); // name of your attachment

        // join attachment and message into one object
        Multipart multipart = new MimeMultipart(); 
        multipart.addBodyPart(messagePart);
        multipart.addBodyPart(attachmentPart);

        message.setContent(multipart);   

        // connect with smtp server
        transport.connect();
        // send your message with attachment
        transport.sendMessage(message,
                message.getRecipients(Message.RecipientType.TO));
        transport.close();
    }

    private class SMTPAuthenticator extends javax.mail.Authenticator {

        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            String username = SMTP_AUTH_USER;
            String password = SMTP_AUTH_PWD;
            return new PasswordAuthentication(username, password);
        }
    }



Is This A Good Question/Topic? 0
  • +

Replies To: Sending email via gmail smtp

#2 Dworza   User is offline

  • D.I.C Head
  • member icon

Reputation: 6
  • View blog
  • Posts: 172
  • Joined: 13-February 11

Re: Sending email via gmail smtp

Posted 19 January 2012 - 10:00 PM

Description: At first you'll need to have some gmail account, because authorization from gmail smtp server is required. Implementation should be easy - main(String[] args) is included, so you can use it as a single project. There is a class called SMTPAuthenticator, which is used only for easier work with data for authorization. You'll also probably have to include javax.jar into your project.This is a class that allows you to send email with attachment via gmail smtp servers.
package net.dreamincode.emailsample

import java.util.Date;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;

public class SimpleMail {

    private static final String SMTP_HOST_NAME = "smtp.gmail.com"; // set the smtp server
    private static final String SMTP_AUTH_USER = "gmailUserName"; // fill in your gmail account user name
    private static final String SMTP_AUTH_PWD = "gmailUserPassword"; // fill in your gmail account password

    public static void main(String[] args) throws Exception {
        new SimpleMail().sendMail();
    }

    public void sendMail() throws Exception {

        //
        // Set the informations about transfer
        //
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.debug", "true");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");

        Authenticator auth = new SMTPAuthenticator();
        Session session = Session.getDefaultInstance(props, auth);
        Transport transport = session.getTransport();

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("[email protected]")); //displaied sender
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); //recepient
        message.setSubject("Some subject"); //subject of your email
        message.setSentDate(new Date()); //date, when was the email sent
      
        MimeBodyPart messagePart = new MimeBodyPart();
        messagePart.setText("Some text displaied in the body of your email");

        //
        // Set the email attachment file
        //
        MimeBodyPart attachmentPart = new MimeBodyPart();
        // tries to find file named "newimage.jpg"
        // when there is no such file, the programm crashes..you should better handle this with some condition
        FileDataSource fileDataSource = new FileDataSource("newimage.jpg") {
            @Override
            public String getContentType() {
                return "application/octet-stream";
            }
        };
        
        attachmentPart.setDataHandler(new DataHandler(fileDataSource));
        attachmentPart.setFileName("newimage.jpg"); // name of your attachment

        // join attachment and message into one object
        Multipart multipart = new MimeMultipart(); 
        multipart.addBodyPart(messagePart);
        multipart.addBodyPart(attachmentPart);

        message.setContent(multipart);   

        // connect with smtp server
        transport.connect();
        // send your message with attachment
        transport.sendMessage(message,
                message.getRecipients(Message.RecipientType.TO));
        transport.close();
    }

    private class SMTPAuthenticator extends javax.mail.Authenticator {

        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            String username = SMTP_AUTH_USER;
            String password = SMTP_AUTH_PWD;
            return new PasswordAuthentication(username, password);
        }
    }

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1