Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java mail gmail

Tags:

java

email

gmail

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 = "[email protected]";
    String to = "[email protected]";
    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!

like image 288
Nick Avatar asked Sep 11 '12 14:09

Nick


People also ask

Can we send email using Java?

Sending emails using Simple Java Mail is pretty straightforward. First, you need to create an email object using EmailBuilder . Then, you need to create a mailer object using MailerBuilder and pass the email object to the mailer object to send the email.

Can I relay through Gmail?

If your organization uses Microsoft Exchange or another SMTP service or server, you can set up the SMTP relay service to route outgoing mail through Google. You can use it to: Filter messages for spam and viruses before they reach external recipients. Apply email security and advanced Gmail settings to outgoing ...


1 Answers

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

like image 73
Nick Avatar answered Sep 23 '22 21:09

Nick