diff src/goodjava/mail/Message.java @ 1583:1cc6c7fa803d

mail work
author Franklin Schmidt <fschmidt@gmail.com>
date Sun, 07 Mar 2021 02:22:09 -0700
parents
children d3728e3e5af3
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/goodjava/mail/Message.java	Sun Mar 07 02:22:09 2021 -0700
@@ -0,0 +1,76 @@
+package goodjava.mail;
+
+import java.util.Map;
+import java.util.LinkedHashMap;
+import java.util.regex.Pattern;
+import java.util.regex.Matcher;
+import goodjava.util.GoodUtils;
+
+import java.net.Socket;
+
+
+public class Message {
+	public final Map<String,String> headers = new LinkedHashMap<String,String>();
+	public final String content;
+	public final String contentType;
+	private static Pattern line = Pattern.compile("(?m)^.*$");
+
+	public Message(String content) {
+		this(content,"text/plain");
+	}
+
+	public Message(String content,String contentType) {
+		this.content = content;
+		this.contentType = contentType;
+	}
+
+	public String toText() {
+		StringBuilder sb = new StringBuilder();
+		for( Map.Entry<String,String> entry : headers.entrySet() ) {
+			String name = entry.getKey();
+			if( name.equalsIgnoreCase("bcc") )
+				continue;
+			String value = entry.getValue();
+			sb.append( name ).append( ": " ).append( value ).append( "\r\n" );
+		}
+		sb.append( "Content-Type: " ).append( contentType ).append( "; charset=\"UTF-8\"\r\n" );
+		boolean isAscii = content.matches("\\p{ASCII}*");
+		if( !isAscii )
+			sb.append( "Content-Transfer-Encoding: base64\r\n" );
+		sb.append( "\r\n" );
+		if( isAscii ) {
+			Matcher m = line.matcher(content);
+			while( m.find() ) {
+				sb.append(m.group()).append("\r\n");		
+			}
+		} else {
+			String s = GoodUtils.base64Encode(content);
+			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");
+		}
+		return sb.toString();
+	}
+
+	public static void main(String[] args) throws Exception {
+		String text = ""
+			+"testm 2\n"
+			+"x\n"
+//			+"产品\n"
+			+"rg; ;lrg dsl rgj errlgerrg neskrjg skrg rdsg drskrg sd;gr s;kgr skrg skrg sdg ds fg;ks gegr erg ;sg sd; g;sdr gsklrg sg s;kkrg s;hg ;slrg ;elrg ;reg r;g ;r g;er g;ler g;e g; g;r g rg; srkd fjl kj kklsjrg lsk gskdf;rs gkrj glj grekjs lksjgkjn kjslg rklrg ;rsd; kj drsg akrglk kalrgklrsdnrgkgj;r ;s ns b;n;sn ;njslk r;n\r\n"
+		;
+		Message msg = new Message(text);
+		msg.headers.put("From","smtp@luan.software");
+		msg.headers.put("To","fschmidt@gmail.com");
+		msg.headers.put("Subject","test");
+		Socket socket = new Socket("smtpcorp.com",2525);
+		Smtp smtp = new Smtp(socket);
+		smtp.authenticate("smtp@luan.software","luanhost");
+		smtp.send(msg);
+		smtp.close();
+		System.out.println("done msg");
+	}
+}