1 38 39 import java.util.*; 40 import java.io.*; 41 import javax.mail.*; 42 import javax.mail.internet.*; 43 import javax.activation.*; 44 45 57 public class msgsendsample { 58 static String msgText = "This is a message body.\nHere's the second line."; 59 60 public static void main(String [] args) { 61 if (args.length != 4) { 62 usage(); 63 System.exit(1); 64 } 65 66 System.out.println(); 67 68 String to = args[0]; 69 String from = args[1]; 70 String host = args[2]; 71 boolean debug = Boolean.valueOf(args[3]).booleanValue(); 72 73 Properties props = new Properties(); 75 props.put("mail.smtp.host", host); 76 if (debug) props.put("mail.debug", args[3]); 77 78 Session session = Session.getInstance(props, null); 79 session.setDebug(debug); 80 81 try { 82 Message msg = new MimeMessage(session); 84 msg.setFrom(new InternetAddress(from)); 85 InternetAddress[] address = {new InternetAddress(args[0])}; 86 msg.setRecipients(Message.RecipientType.TO, address); 87 msg.setSubject("JavaMail APIs Test"); 88 msg.setSentDate(new Date()); 89 msg.setText(msgText); 92 93 Transport.send(msg); 94 } catch (MessagingException mex) { 95 System.out.println("\n--Exception handling in msgsendsample.java"); 96 97 mex.printStackTrace(); 98 System.out.println(); 99 Exception ex = mex; 100 do { 101 if (ex instanceof SendFailedException) { 102 SendFailedException sfex = (SendFailedException)ex; 103 Address[] invalid = sfex.getInvalidAddresses(); 104 if (invalid != null) { 105 System.out.println(" ** Invalid Addresses"); 106 if (invalid != null) { 107 for (int i = 0; i < invalid.length; i++) 108 System.out.println(" " + invalid[i]); 109 } 110 } 111 Address[] validUnsent = sfex.getValidUnsentAddresses(); 112 if (validUnsent != null) { 113 System.out.println(" ** ValidUnsent Addresses"); 114 if (validUnsent != null) { 115 for (int i = 0; i < validUnsent.length; i++) 116 System.out.println(" "+validUnsent[i]); 117 } 118 } 119 Address[] validSent = sfex.getValidSentAddresses(); 120 if (validSent != null) { 121 System.out.println(" ** ValidSent Addresses"); 122 if (validSent != null) { 123 for (int i = 0; i < validSent.length; i++) 124 System.out.println(" "+validSent[i]); 125 } 126 } 127 } 128 System.out.println(); 129 if (ex instanceof MessagingException) 130 ex = ((MessagingException)ex).getNextException(); 131 else 132 ex = null; 133 } while (ex != null); 134 } 135 } 136 137 private static void usage() { 138 System.out.println("usage: java msgsendsample <to> <from> <smtp> true|false"); 139 } 140 } 141 | Popular Tags |