1 19 package org.lucane.applications.sendmail; 20 21 import java.util.*; 22 import java.io.*; 23 24 import javax.mail.*; 25 import javax.mail.internet.*; 26 import javax.activation.*; 27 28 31 public class SendableMail 32 { 33 private MimeMultipart mime; 34 private MimeMessage message; 35 private ArrayList tempfiles; 36 37 41 public SendableMail() 42 { 43 tempfiles = new ArrayList(); 44 45 Properties props = new Properties(); 47 props.put("mail.smtp.host", SendMailService.SMTP_HOST); 48 Session session = Session.getDefaultInstance(props); 49 50 message = new MimeMessage(session); 52 mime = new MimeMultipart(); 53 } 54 55 60 public void setFrom(String from) 61 throws MessagingException 62 { 63 message.setFrom(new InternetAddress(from)); 64 } 65 66 71 public void setSubject(String subject) 72 throws MessagingException 73 { 74 message.setSubject(subject, "iso-8859-15"); 75 } 76 77 82 public void addTo(String to) 83 throws MessagingException 84 { 85 StringTokenizer str = new StringTokenizer(to, ";,"); 86 while (str.hasMoreElements()) 87 message.addRecipient(Message.RecipientType.TO, new InternetAddress((String )str.nextElement())); 88 } 89 90 95 public void addCc(String cc) 96 throws MessagingException 97 { 98 StringTokenizer str = new StringTokenizer(cc, ";,"); 99 while (str.hasMoreElements()) 100 message.addRecipient(Message.RecipientType.CC, new InternetAddress((String )str.nextElement())); 101 } 102 103 108 public void addBcc(String bcc) 109 throws MessagingException 110 { 111 StringTokenizer str = new StringTokenizer(bcc, ";,"); 112 while (str.hasMoreElements()) 113 message.addRecipient(Message.RecipientType.BCC, new InternetAddress((String )str.nextElement())); 114 } 115 116 122 public void setContent(String content, String type) 123 throws MessagingException 124 { 125 MimeBodyPart mbp = new MimeBodyPart(); 126 mbp.setContent(content, type); 127 mime.addBodyPart(mbp); 128 } 129 130 133 protected void finalize() throws Throwable 134 { 135 for (int i = 0; i < tempfiles.size(); i++) 136 ((File)tempfiles.get(i)).delete(); 137 } 138 139 145 public void attach(String filename, String content) 146 throws IOException, MessagingException 147 { 148 MimeBodyPart mbp = new MimeBodyPart(); 149 150 File file = File.createTempFile("mail", ".tmp"); 151 tempfiles.add(file); 152 153 FileWriter fw = null; 154 try { 155 fw = new FileWriter(file); 156 fw.write(content); 157 } finally { 158 if(fw != null) 159 fw.close(); 160 } 161 162 FileDataSource fds = new FileDataSource(file); 163 DataHandler dh = new DataHandler(fds); 164 mbp.setFileName(filename); 165 mbp.setDisposition(Part.ATTACHMENT); 166 mbp.setDataHandler(dh); 167 168 mime.addBodyPart(mbp); 169 } 170 171 174 public void send() 175 throws MessagingException 176 { 177 message.setContent(mime); 178 message.setSentDate(new Date()); 179 Transport.send(message); 180 } 181 } 182 | Popular Tags |