Sending email in Java using Apache Commons email libs

前端 未结 3 1498
小鲜肉
小鲜肉 2021-01-30 18:48

I am using Apache Commons Email library to send emails, but I am not able to send them via GMail SMTP server.
Can anyone provide sample code which works with GMail SMTP serv

3条回答
  •  执笔经年
    2021-01-30 19:41

    Please find below a code which works. Obviously, you have to add the apache jar to your project's build path.

    public static void sendSimpleMail() throws Exception {
        Email email = new SimpleEmail();
        email.setSmtpPort(587);
        email.setAuthenticator(new DefaultAuthenticator("your gmail username",
                "your gmail password"));
        email.setDebug(false);
        email.setHostName("smtp.gmail.com");
        email.setFrom("me@gmail.com");
        email.setSubject("Hi");
        email.setMsg("This is a test mail ... :-)");
        email.addTo("you@gmail.com");
        email.setTLS(true);
        email.send();
        System.out.println("Mail sent!");
    }
    

    Regards, Sergiu

提交回复
热议问题