Hrant Vardanyan
Hrant Vardanyan

Reputation: 253

javax unknown host exception?

Im trying to send eamil using javax. My code is below:

private String emailSender(String emailTo, String emailFrom, String message, String subject, String password) {
    String status = "failed";

    try {
        String ccEmail = "";
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        // Get a Properties object
        Properties props = System.getProperties();
        props.setProperty("mail.smtps.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        props.setProperty("mail.smtps.auth", "true");

        props.put("mail.smtps.quitwait", "false");

        Session session = Session.getInstance(props, null);

        // -- Create a new message --
        final MimeMessage msg = new MimeMessage(session);

        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress(emailFrom));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailTo, false));

        if (ccEmail.length() > 0) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
        }

        msg.setSubject(subject);
        msg.setText(message, "utf-8");
        msg.setSentDate(new Date());

        SMTPTransport t = (SMTPTransport) session.getTransport("smtps");
        String host = StringUtils.substringAfter(emailFrom, "@");
        String emailName = StringUtils.substringBefore(emailFrom, "@");


        t.connect("smtp." + host, emailName, password);
        t.sendMessage(msg, msg.getAllRecipients());
        t.close();
        status = "Sent";
    } catch (Exception e) {
        LOGGER.error("error with sending email ", e);
    }

    return status;
}

Generally it works properly. I can send like via gmail account or yahoo ... but when i'm trying to send from [email protected] account, got unknown host exception like this:

javax.mail.MessagingException: Unknown SMTP host: smtp.vayg.com;

Any solutions?

Upvotes: 0

Views: 176

Answers (2)

BDRSuite
BDRSuite

Reputation: 1612

Get your smtp host name and the port from your admin and then use it in your code.

Eg: as you mentioned in your code, gmail has its own domain and port numbers.

add the appropriate host name and port number in your properties file and then try running your code.

Upvotes: 0

spudone
spudone

Reputation: 1277

You're assuming the host has a 3rd level domain and always prefix it with "smtp."

But that might not always be the case. The smtp host name could be anything.

Upvotes: 1

Related Questions