1 7 package org.contineo.communication; 8 9 import java.util.Collection ; 10 import java.util.Iterator ; 11 import java.util.Properties ; 12 13 import javax.activation.DataHandler ; 14 import javax.activation.DataSource ; 15 import javax.activation.FileDataSource ; 16 import javax.mail.Address ; 17 import javax.mail.Multipart ; 18 import javax.mail.Session ; 19 import javax.mail.Transport ; 20 import javax.mail.internet.InternetAddress ; 21 import javax.mail.internet.MimeBodyPart ; 22 import javax.mail.internet.MimeMessage ; 23 import javax.mail.internet.MimeMultipart ; 24 25 import org.contineo.core.config.SettingConfigurator; 26 32 public class EMailSender { 33 34 37 public EMailSender() { 38 } 39 40 47 public void send(EMailAccount account, EMail email) throws Exception { 48 Properties props = new Properties (); 49 props.put( "mail.smtp.host", account.getSmtpHost() ); 50 props.put( "mail.smtp.auth", "true" ); 51 Session sess = Session.getDefaultInstance(props); 52 javax.mail.Message message = new MimeMessage (sess); 53 InternetAddress from = new InternetAddress (account.getMailAddress()); 54 InternetAddress [] to = email.getAddresses(); 55 message.setFrom(from); 56 message.setRecipients(javax.mail.Message.RecipientType.TO, to); 57 message.setSubject(email.getSubject()); 58 if (email.getAttachmentCount() > 0) { 59 SettingConfigurator conf = new SettingConfigurator(); 60 String userdir = conf.getValue("userdir"); 61 String filename = userdir + "/" + account.getUserName() + "/mails/" + email.getMessageId() + "/"; 62 MimeBodyPart body = new MimeBodyPart (); 63 body.setContent(email.getMessageText(), "text/plain"); 64 Multipart mpMessage = new MimeMultipart (); 65 mpMessage.addBodyPart(body); 66 Collection attachments = email.getAttachments(); 67 Iterator iter = attachments.iterator(); 68 while (iter.hasNext()) { 69 Attachment att = (Attachment)iter.next(); 70 DataSource fdSource = new FileDataSource (filename + att.getFilename()); 71 DataHandler fdHandler = new DataHandler (fdSource); 72 MimeBodyPart part = new MimeBodyPart (); 73 part.setDataHandler(fdHandler); 74 part.setFileName(att.getFilename()); 75 mpMessage.addBodyPart(part); 76 } 77 message.setContent(mpMessage); 78 } else { 79 message.setContent(email.getMessageText(), "text/plain"); 80 } 81 Transport trans = sess.getTransport("smtp"); 82 trans.connect(account.getSmtpHost(), account.getAccountUser(), account.getAccountPassword()); 83 Address adr[] = message.getAllRecipients(); 84 trans.sendMessage(message, adr); 85 trans.close(); 86 } 87 } 88 | Popular Tags |