Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <dependency>
- <groupId>dnsjava</groupId>
- <artifactId>dnsjava</artifactId>
- <version>2.0.1</version>
- </dependency>
- 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];
- }
- 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);
- }
Add Comment
Please, Sign In to add comment