5

I want to send a mail in my java program trough google's smtp server, but it seems stuck at sending the mail. Can someone tell me why pls?

this is the function to send the mail:

     public void sendMail(){
            String from = "xxx@gmail.com";
    String to = "xxx@hotmail.com";
    String subject = "Test";
    String message = "A test message";

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

And this is the class

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.auth", "true");
    props.setProperty( "mail.smtp.port", "587" );
    props.put("mail.smtp.starttls.enable", "true");
    Session session = Session.getDefaultInstance(props);

    new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(from, "MyPasswordGoesHere");
    }
      };

  try {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(text);

    Transport.send(message);
    System.out.println("message sent successfully");
    } catch (MessagingException e) {
    throw new RuntimeException(e);
     }
      }
        }

Thanks in advance!

3
  • ¿Does it raise any error or it just ends without complaining? Set debug on SMTP to see what the client does.
    – Alfabravo
    Sep 11, 2012 at 14:18
  • check this, might help you ... javabeat.net/2007/10/sending-mail-from-java
    – NoNaMe
    Sep 11, 2012 at 14:22
  • @sf shah i used that as example and it doesn't end it just hangs at "Transport.send(message); line
    – Nick
    Sep 11, 2012 at 14:29

2 Answers 2

5

OK i solved it by using this code: http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/

0

In my blog post, I tried to exemplify of sending e-mail messages with Java over Gmail's SMTP server. There are 2 sample codes here. One of them uses Java Mail API while the other exploits Apache Commons Mail library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.