hey.
i want to send a mail from my java application.

the code below works fine except that it results in authentication error in runtime..

here is the code..

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMail {

    private String from;
    private String to;
    private String subject;
    private String text;

    public SendMail(String from, String to, String subject, String text){
        this.from = from;
        this.to = to;
        this.subject = subject;
        this.text = text;
    }

    public void send(){

        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "25");

        Session mailSession = Session.getDefaultInstance(props);
        Message simpleMessage = new MimeMessage(mailSession);

        InternetAddress fromAddress = null;
        InternetAddress toAddress = null;
        try {
            fromAddress = new InternetAddress(from);
            toAddress = new InternetAddress(to);
        } catch (AddressException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            simpleMessage.setFrom(fromAddress);
            simpleMessage.setRecipient(RecipientType.TO, toAddress);
            simpleMessage.setSubject(subject);
            simpleMessage.setText(text);

            Transport.send(simpleMessage);          
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
    }
}

and the MAIN PROGRAM is as follows..

public class SendMailTest {

    public static void main(String[] args) {

        String from = "abc@gmail.com";
        String to = "xyz@gmail.com";
        String subject = "Test";
        String message = "A test message";

        SendMail sendMail = new SendMail(from, to, subject, message);
        sendMail.send();
    }
}

G-mail needs authentication,

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

private class GMailAuthenticator extends javax.mail.Authenticator {
            public PasswordAuthentication getPasswordAuthentication() {
                String user = "username@gmail.com";
                String pwd = "password";
                return new PasswordAuthentication(user, pwd);
            }

And you need to change session to

Session mailSession = Session.getInstance(props, new GMailAuthenticator());

and add this

props.put("mail.smtp.auth", "true");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.