1583
|
1 package goodjava.mail;
|
|
2
|
|
3 import java.util.Map;
|
1584
|
4 import java.util.Base64;
|
1583
|
5 import java.util.regex.Pattern;
|
|
6 import java.util.regex.Matcher;
|
|
7 import goodjava.util.GoodUtils;
|
|
8
|
|
9
|
|
10 public class Message {
|
1584
|
11 public final Map<String,String> headers;
|
|
12 public final Object content;
|
1583
|
13 private static Pattern line = Pattern.compile("(?m)^.*$");
|
|
14
|
1584
|
15 public Message(Map<String,String> headers,Object content) {
|
|
16 this.headers = headers;
|
|
17 this.content = content;
|
1583
|
18 }
|
|
19
|
1584
|
20 private static void addBase64(StringBuilder sb,byte[] a) {
|
|
21 String s = Base64.getEncoder().encodeToString(a);
|
|
22 int n = s.length() - 76;
|
|
23 int i;
|
|
24 for( i=0; i<n; i+=76 ) {
|
|
25 sb.append(s.substring(i,i+76)).append("\r\n");
|
|
26 }
|
|
27 sb.append(s.substring(i)).append("\r\n");
|
1583
|
28 }
|
|
29
|
1584
|
30 public String toText() throws MailException {
|
1583
|
31 StringBuilder sb = new StringBuilder();
|
1584
|
32 String contentType = null;
|
1583
|
33 for( Map.Entry<String,String> entry : headers.entrySet() ) {
|
|
34 String name = entry.getKey();
|
1584
|
35 String value = entry.getValue();
|
1583
|
36 if( name.equalsIgnoreCase("bcc") )
|
|
37 continue;
|
1584
|
38 if( name.equalsIgnoreCase("content-type") ) {
|
|
39 contentType = value;
|
|
40 continue;
|
|
41 }
|
1583
|
42 sb.append( name ).append( ": " ).append( value ).append( "\r\n" );
|
|
43 }
|
1584
|
44 if( contentType==null )
|
|
45 throw new MailException("Content-Type not defined");
|
|
46 if( content instanceof String ) {
|
|
47 String s = (String)content;
|
|
48 sb.append( "Content-Type: " ).append( contentType ).append( "\r\n" );
|
|
49 boolean isAscii = s.matches("\\p{ASCII}*");
|
|
50 if( !isAscii )
|
|
51 sb.append( "Content-Transfer-Encoding: base64\r\n" );
|
|
52 sb.append( "\r\n" );
|
|
53 if( isAscii ) {
|
|
54 Matcher m = line.matcher(s);
|
|
55 while( m.find() ) {
|
|
56 sb.append(m.group()).append("\r\n");
|
|
57 }
|
|
58 } else {
|
|
59 addBase64( sb, GoodUtils.getBytes(s,"UTF-8") );
|
1583
|
60 }
|
1584
|
61 } else if( content instanceof byte[] ) {
|
|
62 sb.append( "Content-Type: " ).append( contentType ).append( "\r\n" );
|
|
63 sb.append( "Content-Transfer-Encoding: base64\r\n" );
|
|
64 sb.append( "\r\n" );
|
|
65 addBase64( sb, (byte[])content );
|
|
66 } else
|
|
67 throw new MailException("content is unrecognized type");
|
1583
|
68 return sb.toString();
|
|
69 }
|
|
70 }
|