Dave Jarvis' Repositories

git clone https://repo.autonoma.ca/repo/sales.git

Extract message contents...

Author djarvis <email>
Date 2016-06-03 21:23:46 GMT-0700
Commit 8b7ce861b3aaa34532e9b7b435abd4621542aa2d
Parent 1ff6e97
src/main/java/com/whitemagicsoftware/notify/HttpTransport.java
import java.net.URLConnection;
import java.net.URLEncoder;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
import javax.mail.Address;
+import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
+import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.URLName;
+import javax.mail.internet.MimeMultipart;
/**
*/
public HttpTransport( Session session, URLName urlname ) {
+ // This should set the protected instance variables of "this.session"
+ // and "this.urlname".
super( session, urlname );
+ }
+
+ protected Charset defaultEncoding() {
+ return StandardCharsets.UTF_8;
+ }
+
+ private String encode( String text ) throws UnsupportedEncodingException {
+ return URLEncoder.encode( text, defaultEncoding().displayName() );
}
/**
+ * Returns the first sender on the list of senders for a given message. This
+ * will ignore all other senders (if set).
*
- * @param message
- * @param addresses
+ * @param message The message to extract the first sender.
*
- * @throws javax.mail.MessagingException Error sending the message.
+ * @return "" if there were no senders, otherwise the first on the list.
+ *
+ * @throws MessagingException
+ */
+ private String getSender( Message message ) throws MessagingException {
+ Address senders[] = message.getFrom();
+
+ if( senders.length > 0 ) {
+ return senders[ 1 ].toString();
+ }
+
+ return "";
+ }
+
+ /**
+ *
+ * @param message Message that contains content to extract.
+ *
+ * @return
+ *
+ * @throws Exception
+ * @see http://stackoverflow.com/a/34689614/59087
+ */
+ private String extractBody( Message message )
+ throws MessagingException {
+ String result = "";
+
+ try {
+ Object content = message.getContent();
+
+ if( message.isMimeType( "text/plain" ) ) {
+ result = content.toString();
+ } else if( message.isMimeType( "multipart/*" ) ) {
+ result = extractMimeMultipart( (MimeMultipart) content );
+ }
+ } catch( IOException e ) {
+ throw new MessagingException( "Could not extract message content.", e );
+ }
+
+ return result;
+ }
+
+ private String extractMimeMultipart(
+ MimeMultipart mimeMultipart ) throws MessagingException {
+ String result = "";
+ int count = mimeMultipart.getCount();
+
+ for( int i = 0; i < count; i++ ) {
+ BodyPart bodyPart = mimeMultipart.getBodyPart( i );
+ Object content = extractBodyPart( bodyPart );
+
+ if( bodyPart.isMimeType( "text/plain" ) ) {
+ result += "\n" + content;
+
+ // Avoid doubling-up text.
+ break;
+ } else if( bodyPart.isMimeType( "text/html" ) ) {
+ String html = content.toString();
+ result += "\n" + org.jsoup.Jsoup.parse( html ).text();
+ } else if( content instanceof MimeMultipart ) {
+ result += extractMimeMultipart( (MimeMultipart) content );
+ }
+ }
+
+ return result;
+ }
+
+ private Object extractBodyPart( BodyPart bodyPart )
+ throws MessagingException {
+ try {
+ return bodyPart.getContent();
+ } catch( IOException e ) {
+ throw new MessagingException( "Error opening body part contents.", e );
+ }
+ }
+
+ private String extractSubject( Message message ) throws MessagingException {
+ return message.getSubject();
+ }
+
+ /**
+ * Sends a message to one or more addresses.
+ *
+ * @param message The message to send.
+ * @param addresses The list of recipients who receive the message.
+ *
+ * @throws MessagingException Error sending the message.
*/
@Override
- public void sendMessage( Message message, Address[] addresses ) throws MessagingException {
- String userName = "";
- String apiKey = "";
- String from = "";
+ public void sendMessage( Message message, Address[] addresses )
+ throws MessagingException {
+
+ String userName = getUsername();
+ String apiKey = getApiKey();
+
+ String from = getSender( message );
String fromName = "";
- String subject = "";
- String body = "";
- String to = "";
+ String subject = extractSubject( message );
+ String body = extractBody( message );
+ String to = addresses[ 0 ].toString();
String data = "";
try {
- data = "userName=" + URLEncoder.encode( userName, "UTF-8" );
- data += "&api_key=" + URLEncoder.encode( apiKey, "UTF-8" );
- data += "&from=" + URLEncoder.encode( from, "UTF-8" );
- data += "&from_name=" + URLEncoder.encode( fromName, "UTF-8" );
- data += "&subject=" + URLEncoder.encode( subject, "UTF-8" );
- data += "&body_html=" + URLEncoder.encode( body, "UTF-8" );
- data += "&to=" + URLEncoder.encode( to, "UTF-8" );
+ data = "userName=" + encode( userName );
+ data += "&api_key=" + encode( apiKey );
+ data += "&from=" + encode( from );
+ data += "&from_name=" + encode( fromName );
+ data += "&subject=" + encode( subject );
+ data += "&body_html=" + encode( body );
+ data += "&to=" + encode( to );
} catch( UnsupportedEncodingException e ) {
throw new MessagingException( "Could not encode parameters.", e );
throw new MessagingException( "Provider URL not set.", e );
}
+ }
+
+ private PasswordAuthentication getPasswordAuthentication() {
+ return getSession().getPasswordAuthentication( getURLName() );
+ }
+
+ private String getUsername() {
+ return getPasswordAuthentication().getUserName();
+ }
+
+ private String getApiKey() {
+ return getPasswordAuthentication().getPassword();
+ }
+
+ private Session getSession() {
+ return this.session;
}
}
src/test/java/com/whitemagicsoftware/notify/test/HttpTransportTests.java
public class HttpTransportTests {
+ private static final String REST_API_URL
+ = "https://api.elasticemail.com/mailer/send";
+
public HttpTransportTests() {
}
@Test
- public void testNotify() {
+ public void testNotify() throws MessagingException {
try {
- URL url = new URL( "https://api.elasticemail.com/mailer/send" );
-
- Properties properties = new Properties();
-
- createAuthenticator(
- USERNAME,
- PASSWORD );
-
- URLName urlName = new URLName( url );
- Session session = Session.getDefaultInstance( properties );
+ URLName urlName = createURLName();
+ Session session = createSession();
HttpTransport transport = new HttpTransport( session, urlName );
Message message = new MimeMessage( session );
- Address sender = new InternetAddress( "sender@address.com", "Sender Name" );
- Address recipient = new InternetAddress( "recipient@address.com" );
-
+ Address sender = new InternetAddress( "Penny.Savr@gmail.com", "Penny Saver" );
+ Address recipient = new InternetAddress( "Dave.Jarvis@gmail.com" );
+
message.setFrom( sender );
message.addRecipient( Message.RecipientType.TO, recipient );
message.setSubject( "Subject" );
message.setText( "Body" );
transport.sendMessage( message, message.getAllRecipients() );
transport.close();
- } catch( MalformedURLException | UnsupportedEncodingException |
- MessagingException e ) {
+ } catch( UnsupportedEncodingException e ) {
Assert.fail( e.getMessage() );
+ }
+ }
+
+ private URL createRestApiUrl() throws MalformedURLException {
+ return new URL( REST_API_URL );
+ }
+
+ private URLName createURLName() throws MessagingException {
+ try {
+ return new URLName( createRestApiUrl() );
+ } catch( MalformedURLException e ) {
+ throw new MessagingException( "Could not create URL.", e );
}
+ }
+
+ private Session createSession() {
+ return Session.getDefaultInstance(
+ createProperties(),
+ createAuthenticator() );
+ }
+
+ private Properties createProperties() {
+ return new Properties();
}
* @return A non-null Authenticator instance.
*/
- private Authenticator createAuthenticator(
- final Credentials user, final Credentials pass ) {
+ private Authenticator createAuthenticator() {
return new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication( user.toString(), pass.toString() );
+ return new PasswordAuthentication(
+ USERNAME.toString(),
+ PASSWORD.toString() );
}
};
Delta 174 lines added, 36 lines removed, 138-line increase