简体   繁体   中英

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 contact@vayg.com account, got unknown host exception like this:

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

Any solutions?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM