diff src/goodjava/mail/Message.java @ 1585:c0ef8acf069d

multipart mail
author Franklin Schmidt <fschmidt@gmail.com>
date Fri, 12 Mar 2021 18:06:15 -0700
parents d3728e3e5af3
children fa1a9aceac3e
line wrap: on
line diff
--- a/src/goodjava/mail/Message.java	Thu Mar 11 01:22:20 2021 -0700
+++ b/src/goodjava/mail/Message.java	Fri Mar 12 18:06:15 2021 -0700
@@ -2,14 +2,15 @@
 
 import java.util.Map;
 import java.util.Base64;
+import java.util.Random;
 import java.util.regex.Pattern;
 import java.util.regex.Matcher;
 import goodjava.util.GoodUtils;
 
 
 public class Message {
-	public final Map<String,String> headers;
-	public final Object content;
+	final Map<String,String> headers;
+	final Object content;
 	private static Pattern line = Pattern.compile("(?m)^.*$");
 
 	public Message(Map<String,String> headers,Object content) {
@@ -63,8 +64,31 @@
 			sb.append( "Content-Transfer-Encoding: base64\r\n" );
 			sb.append( "\r\n" );
 			addBase64( sb, (byte[])content );
+		} else if( content instanceof Message[] ) {
+			Message[] messages = (Message[])content;
+			String[] texts = new String[messages.length];
+			StringBuilder allTextSb = new StringBuilder();
+			for( int i=0; i<messages.length; i++ ) {
+				String text = messages[i].toText();
+				texts[i] = text;
+				allTextSb.append(text);
+			}
+			String allText = allTextSb.toString();
+			String boundary;
+			do {
+				boundary = Long.toHexString(new Random().nextLong());
+			} while( allText.contains(boundary) );
+			sb.append( "Content-Type: " ).append( contentType )
+				.append( "; boundary=\"" ).append( boundary ).append( "\"\r\n" );
+			sb.append( "\r\n" );
+			for( String text : texts ) {
+				sb.append( "--" ).append( boundary ).append( "\r\n" );
+				sb.append( text );
+				sb.append( "\r\n" );
+			}
+			sb.append( "--" ).append( boundary ).append( "--\r\n" );
 		} else
-			throw new MailException("content is unrecognized type");
+			throw new MailException("content is unrecognized type: "+content.getClass());
 		return sb.toString();
 	}
 }