view src/goodjava/mail/Message.java @ 1584:d3728e3e5af3

mail work
author Franklin Schmidt <fschmidt@gmail.com>
date Thu, 11 Mar 2021 01:22:20 -0700
parents 1cc6c7fa803d
children c0ef8acf069d
line wrap: on
line source

package goodjava.mail;

import java.util.Map;
import java.util.Base64;
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;
	private static Pattern line = Pattern.compile("(?m)^.*$");

	public Message(Map<String,String> headers,Object content) {
		this.headers = headers;
		this.content = content;
	}

	private static void addBase64(StringBuilder sb,byte[] a) {
		String s = Base64.getEncoder().encodeToString(a);
		int n = s.length() - 76;
		int i;
		for( i=0; i<n; i+=76 ) {
			sb.append(s.substring(i,i+76)).append("\r\n");
		}
		sb.append(s.substring(i)).append("\r\n");
	}

	public String toText() throws MailException {
		StringBuilder sb = new StringBuilder();
		String contentType = null;
		for( Map.Entry<String,String> entry : headers.entrySet() ) {
			String name = entry.getKey();
			String value = entry.getValue();
			if( name.equalsIgnoreCase("bcc") )
				continue;
			if( name.equalsIgnoreCase("content-type") ) {
				contentType = value;
				continue;
			}
			sb.append( name ).append( ": " ).append( value ).append( "\r\n" );
		}
		if( contentType==null )
			throw new MailException("Content-Type not defined");
		if( content instanceof String ) {
			String s = (String)content;
			sb.append( "Content-Type: " ).append( contentType ).append( "\r\n" );
			boolean isAscii = s.matches("\\p{ASCII}*");
			if( !isAscii )
				sb.append( "Content-Transfer-Encoding: base64\r\n" );
			sb.append( "\r\n" );
			if( isAscii ) {
				Matcher m = line.matcher(s);
				while( m.find() ) {
					sb.append(m.group()).append("\r\n");		
				}
			} else {
				addBase64( sb, GoodUtils.getBytes(s,"UTF-8") );
			}
		} else if( content instanceof byte[] ) {
			sb.append( "Content-Type: " ).append( contentType ).append( "\r\n" );
			sb.append( "Content-Transfer-Encoding: base64\r\n" );
			sb.append( "\r\n" );
			addBase64( sb, (byte[])content );
		} else
			throw new MailException("content is unrecognized type");
		return sb.toString();
	}
}