Someone knows a mail (SMTP) delivery library for Java?

前端 未结 3 1750
生来不讨喜
生来不讨喜 2021-02-03 11:51

I\'d like to send mail without bothering with the SMTP-Server which is used for delivery.

So JavaMail API doesn\'t work for me because I have to specify a SMTP server to

3条回答
  •  萌比男神i
    2021-02-03 12:15

    One possible solution: get the MX record on your own and use JavaMail API.

    You can get the MX record using the dnsjava project:

    Maven2 dependency:

    
        dnsjava
        dnsjava
        2.0.1
    
    

    Method for MX record retrieval:

    public static String getMXRecordsForEmailAddress(String eMailAddress) {
        String returnValue = null;
    
        try {
            String hostName = getHostNameFromEmailAddress(eMailAddress);
            Record[] records = new Lookup(hostName, Type.MX).run();
            if (records == null) { throw new RuntimeException("No MX records found for domain " + hostName + "."); }
    
            if (log.isTraceEnabled()) {
                // log found entries for debugging purposes
                for (int i = 0; i < records.length; i++) {
                    MXRecord mx = (MXRecord) records[i];
                    String targetString = mx.getTarget().toString();
                    log.trace("MX-Record for '" + hostName + "':" + targetString);
                }
            }
    
            // return first entry (not the best solution)
            if (records.length > 0) {
                MXRecord mx = (MXRecord) records[0];
                returnValue = mx.getTarget().toString();
            }
        } catch (TextParseException e) {
            throw new RuntimeException(e);
        }
    
        if (log.isTraceEnabled()) {
            log.trace("Using: " + returnValue);
        }
        return returnValue;
    }
    
    private static String getHostNameFromEmailAddress(String mailAddress) throws TextParseException {
        String parts[] = mailAddress.split("@");
        if (parts.length != 2) throw new TextParseException("Cannot parse E-Mail-Address: '" + mailAddress + "'");
        return parts[1];
    }
    

    Sending mail via JavaMail code:

    public static void sendMail(String toAddress, String fromAddress, String subject, String body) throws AddressException, MessagingException {
        String smtpServer = getMXRecordsForEmailAddress(toAddress);
    
        // create session
        Properties props = new Properties();
        props.put("mail.smtp.host", smtpServer);
        Session session = Session.getDefaultInstance(props);
    
        // create message
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromAddress));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
        msg.setSubject(subject);
        msg.setText(body);
    
        // send message
        Transport.send(msg);
    }
    

提交回复
热议问题