code_junkie

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

Nov 12th, 2011
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. <dependency>
  2. <groupId>dnsjava</groupId>
  3. <artifactId>dnsjava</artifactId>
  4. <version>2.0.1</version>
  5. </dependency>
  6.  
  7. public static String getMXRecordsForEmailAddress(String eMailAddress) {
  8. String returnValue = null;
  9.  
  10. try {
  11. String hostName = getHostNameFromEmailAddress(eMailAddress);
  12. Record[] records = new Lookup(hostName, Type.MX).run();
  13. if (records == null) { throw new RuntimeException("No MX records found for domain " + hostName + "."); }
  14.  
  15. if (log.isTraceEnabled()) {
  16. // log found entries for debugging purposes
  17. for (int i = 0; i < records.length; i++) {
  18. MXRecord mx = (MXRecord) records[i];
  19. String targetString = mx.getTarget().toString();
  20. log.trace("MX-Record for '" + hostName + "':" + targetString);
  21. }
  22. }
  23.  
  24. // return first entry (not the best solution)
  25. if (records.length > 0) {
  26. MXRecord mx = (MXRecord) records[0];
  27. returnValue = mx.getTarget().toString();
  28. }
  29. } catch (TextParseException e) {
  30. throw new RuntimeException(e);
  31. }
  32.  
  33. if (log.isTraceEnabled()) {
  34. log.trace("Using: " + returnValue);
  35. }
  36. return returnValue;
  37. }
  38.  
  39. private static String getHostNameFromEmailAddress(String mailAddress) throws TextParseException {
  40. String parts[] = mailAddress.split("@");
  41. if (parts.length != 2) throw new TextParseException("Cannot parse E-Mail-Address: '" + mailAddress + "'");
  42. return parts[1];
  43. }
  44.  
  45. public static void sendMail(String toAddress, String fromAddress, String subject, String body) throws AddressException, MessagingException {
  46. String smtpServer = getMXRecordsForEmailAddress(toAddress);
  47.  
  48. // create session
  49. Properties props = new Properties();
  50. props.put("mail.smtp.host", smtpServer);
  51. Session session = Session.getDefaultInstance(props);
  52.  
  53. // create message
  54. Message msg = new MimeMessage(session);
  55. msg.setFrom(new InternetAddress(fromAddress));
  56. msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
  57. msg.setSubject(subject);
  58. msg.setText(body);
  59.  
  60. // send message
  61. Transport.send(msg);
  62. }
Add Comment
Please, Sign In to add comment