List of usage examples for javax.mail.internet MimeMessage setFrom
public void setFrom(String address) throws MessagingException
From source file:net.spfbl.http.ServerHTTP.java
private static boolean enviarDesbloqueioDNSBL(Locale locale, String url, String ip, String email) throws MessagingException { if (url == null) { return false; } else if (!Core.hasOutputSMTP()) { return false; } else if (!Core.hasAdminEmail()) { return false; } else if (!Domain.isEmail(email)) { return false; } else if (NoReply.contains(email, true)) { return false; } else {// www.j ava 2 s. co m try { Server.logDebug("sending unblock by e-mail."); User user = User.get(email); InternetAddress[] recipients; if (user == null) { recipients = InternetAddress.parse(email); } else { recipients = new InternetAddress[1]; recipients[0] = user.getInternetAddress(); } Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); message.setHeader("Date", Core.getEmailDate()); message.setFrom(Core.getAdminInternetAddress()); message.addRecipients(Message.RecipientType.TO, recipients); String subject; if (locale.getLanguage().toLowerCase().equals("pt")) { subject = "Chave de desbloqueio SPFBL"; } else { subject = "Unblocking key SPFBL"; } message.setSubject(subject); // Corpo da mensagem. StringBuilder builder = new StringBuilder(); builder.append("<!DOCTYPE html>\n"); builder.append("<html lang=\""); builder.append(locale.getLanguage()); builder.append("\">\n"); builder.append(" <head>\n"); builder.append(" <meta charset=\"UTF-8\">\n"); builder.append(" <title>"); builder.append(subject); builder.append("</title>\n"); loadStyleCSS(builder); if (locale.getLanguage().toLowerCase().equals("pt")) { buildConfirmAction(builder, "Desbloquear IP", url, "Confirme o desbloqueio para o IP " + ip + " na DNSBL", "SPFBL.net", "http://spfbl.net/"); } else { buildConfirmAction(builder, "Delist IP", url, "Confirm the delist of IP " + ip + " at DNSBL", "SPFBL.net", "http://spfbl.net/en/"); } builder.append(" </head>\n"); builder.append(" <body>\n"); builder.append(" <div id=\"container\">\n"); builder.append(" <div id=\"divlogo\">\n"); builder.append(" <img src=\"cid:logo\">\n"); builder.append(" </div>\n"); if (locale.getLanguage().toLowerCase().equals("pt")) { buildMessage(builder, "Desbloqueio do IP " + ip + " na DNSBL"); buildText(builder, "Se voc o administrador deste IP, e fez esta solicitao, acesse esta URL e resolva o reCAPTCHA para finalizar o procedimento:"); } else { buildMessage(builder, "Unblock of IP " + ip + " at DNSBL"); buildText(builder, "If you are the administrator of this IP and made this request, go to this URL and solve the reCAPTCHA to finish the procedure:"); } buildText(builder, "<a href=\"" + url + "\">" + url + "</a>"); buildFooter(builder, locale); builder.append(" </div>\n"); builder.append(" </body>\n"); builder.append("</html>\n"); // Making HTML part. MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(builder.toString(), "text/html;charset=UTF-8"); // Making logo part. MimeBodyPart logoPart = new MimeBodyPart(); File logoFile = getWebFile("logo.png"); logoPart.attachFile(logoFile); logoPart.setContentID("<logo>"); logoPart.addHeader("Content-Type", "image/png"); logoPart.setDisposition(MimeBodyPart.INLINE); // Join both parts. MimeMultipart content = new MimeMultipart("related"); content.addBodyPart(htmlPart); content.addBodyPart(logoPart); // Set multiplart content. message.setContent(content); message.saveChanges(); // Enviar mensagem. return Core.sendMessage(message, 30000); } catch (MailConnectException ex) { throw ex; } catch (SendFailedException ex) { throw ex; } catch (MessagingException ex) { throw ex; } catch (Exception ex) { Server.logError(ex); return false; } } }
From source file:net.spfbl.http.ServerHTTP.java
public static boolean enviarOTP(Locale locale, User user) { if (locale == null) { Server.logError("no locale defined."); return false; } else if (!Core.hasOutputSMTP()) { Server.logError("no SMTP account to send TOTP."); return false; } else if (!Core.hasAdminEmail()) { Server.logError("no admin e-mail to send TOTP."); return false; } else if (user == null) { Server.logError("no user definied to send TOTP."); return false; } else if (NoReply.contains(user.getEmail(), true)) { Server.logError("cannot send TOTP because user is registered in noreply."); return false; } else {/* w ww .ja v a 2 s .c o m*/ try { Server.logDebug("sending TOTP by e-mail."); String secret = user.newSecretOTP(); InternetAddress[] recipients = new InternetAddress[1]; recipients[0] = user.getInternetAddress(); Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); message.setHeader("Date", Core.getEmailDate()); message.setFrom(Core.getAdminInternetAddress()); message.addRecipients(Message.RecipientType.TO, recipients); String subject; if (locale.getLanguage().toLowerCase().equals("pt")) { subject = "Chave TOTP do SPFBL"; } else { subject = "SPFBL TOTP key"; } message.setSubject(subject); // Corpo da mensagem. StringBuilder builder = new StringBuilder(); builder.append("<!DOCTYPE html>\n"); builder.append("<html lang=\""); builder.append(locale.getLanguage()); builder.append("\">\n"); builder.append(" <head>\n"); builder.append(" <meta charset=\"UTF-8\">\n"); builder.append(" <title>"); builder.append(subject); builder.append("</title>\n"); loadStyleCSS(builder); builder.append(" </head>\n"); builder.append(" <body>\n"); builder.append(" <div id=\"container\">\n"); builder.append(" <div id=\"divlogo\">\n"); builder.append(" <img src=\"cid:logo\">\n"); builder.append(" </div>\n"); if (locale.getLanguage().toLowerCase().equals("pt")) { buildMessage(builder, "Sua chave <a target=\"_blank\" href=\"http://spfbl.net/totp/\">TOTP</a> no sistema SPFBL em " + Core.getHostname()); buildText(builder, "Carregue o QRCode abaixo em seu Google Authenticator ou em outro aplicativo <a target=\"_blank\" href=\"http://spfbl.net/totp/\">TOTP</a> de sua preferncia."); builder.append(" <div id=\"divcaptcha\">\n"); builder.append(" <img src=\"cid:qrcode\"><br>\n"); builder.append(" "); builder.append(secret); builder.append("\n"); builder.append(" </div>\n"); } else { buildMessage(builder, "Your <a target=\"_blank\" href=\"http://spfbl.net/en/totp/\">TOTP</a> key in SPFBL system at " + Core.getHostname()); buildText(builder, "Load QRCode below on your Google Authenticator or on other application <a target=\"_blank\" href=\"http://spfbl.net/en/totp/\">TOTP</a> of your choice."); builder.append(" <div id=\"divcaptcha\">\n"); builder.append(" <img src=\"cid:qrcode\"><br>\n"); builder.append(" "); builder.append(secret); builder.append("\n"); builder.append(" </div>\n"); } buildFooter(builder, locale); builder.append(" </div>\n"); builder.append(" </body>\n"); builder.append("</html>\n"); // Making HTML part. MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(builder.toString(), "text/html;charset=UTF-8"); // Making logo part. MimeBodyPart logoPart = new MimeBodyPart(); File logoFile = getWebFile("logo.png"); logoPart.attachFile(logoFile); logoPart.setContentID("<logo>"); logoPart.addHeader("Content-Type", "image/png"); logoPart.setDisposition(MimeBodyPart.INLINE); // Making QRcode part. MimeBodyPart qrcodePart = new MimeBodyPart(); String code = "otpauth://totp/" + Core.getHostname() + ":" + user.getEmail() + "?" + "secret=" + secret + "&" + "issuer=" + Core.getHostname(); File qrcodeFile = Core.getQRCodeTempFile(code); qrcodePart.attachFile(qrcodeFile); qrcodePart.setContentID("<qrcode>"); qrcodePart.addHeader("Content-Type", "image/png"); qrcodePart.setDisposition(MimeBodyPart.INLINE); // Join both parts. MimeMultipart content = new MimeMultipart("related"); content.addBodyPart(htmlPart); content.addBodyPart(logoPart); content.addBodyPart(qrcodePart); // Set multiplart content. message.setContent(content); message.saveChanges(); // Enviar mensagem. boolean sent = Core.sendMessage(message, 5000); qrcodeFile.delete(); return sent; } catch (Exception ex) { Server.logError(ex); return false; } } }
From source file:org.sakaiproject.email.impl.BasicEmailService.java
/** * fix up From and ReplyTo if we need it to be from Postmaster *///w w w .ja va 2 s .co m private void checkFrom(MimeMessage msg) { String sendFromSakai = serverConfigurationService.getString(MAIL_SENDFROMSAKAI, "true"); String sendExceptions = serverConfigurationService.getString(MAIL_SENDFROMSAKAI_EXCEPTIONS, null); InternetAddress from = null; InternetAddress[] replyTo = null; try { Address[] fromA = msg.getFrom(); if (fromA == null || fromA.length == 0) { M_log.info("message from missing"); return; } else if (fromA.length > 1) { M_log.info("message from more than 1"); return; } else if (fromA instanceof InternetAddress[]) { from = (InternetAddress) fromA[0]; } else { M_log.info("message from not InternetAddress"); return; } Address[] replyToA = msg.getReplyTo(); if (replyToA == null) replyTo = null; else if (replyToA instanceof InternetAddress[]) replyTo = (InternetAddress[]) replyToA; else { M_log.info("message replyto isn't internet address"); return; } // should we replace from address with a Sakai address? if (sendFromSakai != null && !sendFromSakai.equalsIgnoreCase("false")) { // exceptions -- addresses to leave alone. Our own addresses are always exceptions. // you can also configure a regexp of exceptions. if (!from.getAddress().toLowerCase() .endsWith("@" + serverConfigurationService.getServerName().toLowerCase()) && (sendExceptions == null || sendExceptions.equals("") || !from.getAddress().toLowerCase().matches(sendExceptions))) { // not an exception. do the replacement. // First, decide on the replacement address. The config variable // may be the replacement address. If not, use postmaster if (sendFromSakai.indexOf("@") < 0) sendFromSakai = POSTMASTER + "@" + serverConfigurationService.getServerName(); // put the original from into reply-to, unless a replyto exists if (replyTo == null || replyTo.length == 0 || replyTo[0].getAddress().equals("")) { replyTo = new InternetAddress[1]; replyTo[0] = from; msg.setReplyTo(replyTo); } // for some reason setReplyTo doesn't work, though setFrom does. Have to create the // actual header line if (msg.getHeader(EmailHeaders.REPLY_TO) == null) msg.addHeader(EmailHeaders.REPLY_TO, from.getAddress()); // and use the new from address // biggest issue is the "personal address", i.e. the comment text String origFromText = from.getPersonal(); String origFromAddress = from.getAddress(); String fromTextPattern = serverConfigurationService.getString(MAIL_SENDFROMSAKAI_FROMTEXT, "{}"); String fromText = null; if (origFromText != null && !origFromText.equals("")) fromText = fromTextPattern.replace("{}", origFromText + " (" + origFromAddress + ")"); else fromText = fromTextPattern.replace("{}", origFromAddress); from = new InternetAddress(sendFromSakai); try { from.setPersonal(fromText); } catch (Exception e) { } msg.setFrom(from); } } } catch (javax.mail.internet.AddressException e) { M_log.info("checkfrom address exception " + e); } catch (javax.mail.MessagingException e) { M_log.info("checkfrom messaging exception " + e); } }
From source file:com.riq.MailHandlerServlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { log.info("Inside MailServlet doPost"); // TODO get path information to determine target Department for this email PersistenceManager pm = PMF.get().getPersistenceManager(); Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); try {/*from w w w. j a va 2 s . c om*/ MimeMessage msg = new MimeMessage(session, req.getInputStream()); Address sender = msg.getFrom()[0]; Address replyTo = msg.getReplyTo()[0]; // DEBUG // log.info("Message Class: " + msg.getClass()); // log.info("Message Stream: " + msg.getInputStream()); // log.info("Message RawStream: " + msg.getRawInputStream()); // log.info("Message Flags: " + msg.getFlags()); // log.info("Message Content: " + msg.getContent().toString()); // log.info("Message ContentID: " + msg.getContentID()); // log.info("Message ContentMD: " + msg.getContentMD5()); // log.info("Message ContentType: " + msg.getContentType()); // log.info("Message Description: " + msg.getDescription()); // log.info("Message Disposition: " + msg.getDisposition()); // log.info("Message Encoding: " + msg.getEncoding()); // log.info("Message Filename: " + msg.getFileName()); // log.info("Message Line Count: " + msg.getLineCount()); // log.info("Message ID: " + msg.getMessageID()); // log.info("Message Number: " + msg.getMessageNumber()); // log.info("Message Size: " + msg.getSize()); // log.info("Message Subject: " + msg.getSubject()); // log.info("Message RawInputStream: " + msg.getRawInputStream().toString()); // log.info("Message ReplyTo: " + replyTo); // log.info("Message Sender: " + sender.toString()); // log.info("Request URL TO: " + getServletContext()); String alertMsgString = getText(msg); alertMsgString = alertMsgString.replaceAll("Begin forwarded message:", ""); alertMsgString = alertMsgString.replaceAll("Forwarded message", ""); alertMsgString = alertMsgString.replaceAll("Dispatch@co.morris.nj.us", ""); alertMsgString = alertMsgString.replaceAll("Date:", ""); alertMsgString = alertMsgString.replaceAll(">", ""); alertMsgString = alertMsgString.replaceAll("::", "-"); alertMsgString = alertMsgString.replaceAll("< ", ""); alertMsgString = alertMsgString.replaceAll("----------", ""); alertMsgString = alertMsgString.replaceAll("Subject:", ""); alertMsgString = alertMsgString.replaceAll("To:", ""); alertMsgString = alertMsgString.replaceAll("From:", ""); // Added to grab gmail confirmations // alertMsgString = alertMsgString.substring(50, 300); try { String queryDept = "select from " + Department.class.getName() + // TODO: johnreilly workaround for getting allRecipients... // " where dispatchId == '" + toAddressDigitsOnly + "' " + " where dispatchId == '2599' " + " && fromEmail == '" + sender + "' "; log.info("queryDept: " + queryDept); List<Department> depts = (List<Department>) pm.newQuery(queryDept).execute(); if (depts.size() != 0) { for (Department d : depts) { // need to filter further e.g. last two hours String queryAlert = "select from " + Alert.class.getName() + " where deptId == " + depts.get(0).getid() + " && messageId == '" + msg.getMessageID() + "' "; log.info("queryAlert: " + queryAlert); List<Alert> alerts = (List<Alert>) pm.newQuery(queryAlert).execute(); log.info("queryAlert Result Qty: " + alerts.size()); if (alerts.size() == 0) { riqGeocode(alertMsgString); // geocode the address from the Alert Map<String, String> geoResults = riqGeocode(alertMsgString); log.info("lat print: " + geoResults.get("lat")); log.info("lng print: " + geoResults.get("lng")); // create the alert Long deptId = depts.get(0).getid(); Long timeStamp = System.currentTimeMillis(); Alert a = new Alert(deptId, timeStamp, alertMsgString.trim(), sender.toString(), "Active", "", geoResults.get("lat"), geoResults.get("lng"), msg.getMessageID()); pm.makePersistent(a); // query to get id of this alert String queryThisAlert = "select from " + Alert.class.getName() + " where deptId == " + deptId + " " + " && timeStamp == " + timeStamp; log.info("queryThisAlert: " + queryThisAlert); List<Alert> thisAlert = (List<Alert>) pm.newQuery(queryThisAlert).execute(); log.info("queryCurrentAlert Result Qty: " + thisAlert.size()); // create Tracking records for "special" Locations String querySpecialLocs = "select from " + Location.class.getName() + " where special == 'yes' && deptId == " + deptId; log.info("querySpecialLocs: " + querySpecialLocs); List<Location> specialLocs = (List<Location>) pm.newQuery(querySpecialLocs).execute(); log.info("querySpecialLocs qty: " + specialLocs.size()); for (Location specL : specialLocs) { Tracking tSL = new Tracking(deptId, thisAlert.get(0).getid(), specL.getid(), System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd "location", specL.getid(), null, "autoAddLocation"); pm.makePersistent(tSL); } // search Dept for Location where distant Members presumed not to be responding are set String queryFarawayLocs = "select from " + Location.class.getName() + " where vru == '2' && deptId == " + deptId; log.info("querySpecialLocs: " + queryFarawayLocs); List<Location> farawayLoc = (List<Location>) pm.newQuery(queryFarawayLocs).execute(); log.info("queryFarawayLocs qty: " + farawayLoc.size()); // create Tracking records for Members presumed not to be responder due to fresh ETA String queryFarAwayResponders = "select from " + Member.class.getName() + " where distGroup == '4' "; log.info("queryFarAwayResponders: " + queryFarAwayResponders); List<Member> farawayMembers = (List<Member>) pm.newQuery(queryFarAwayResponders) .execute(); log.info("queryFarAwayResponders qty: " + farawayMembers.size()); if (farawayMembers.size() != 0) { for (Member far : farawayMembers) { Tracking tMFAR = new Tracking(deptId, thisAlert.get(0).getid(), farawayLoc.get(0).getid(), System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd "farawayAddMember", far.getid(), null, responseType); pm.makePersistent(tMFAR); } } // TODO: testing restriction HACKER - remove at launch // send alert email String queryMember = "select from " + Member.class.getName() + " where deptId == " + deptId + " && type == 'Hacker' "; List<Member> members = (List<Member>) pm.newQuery(queryMember).execute(); //TODO Geocode address to insure easy navigation //TODO johnreilly: add street and town fields to Alert msg.setFrom( new InternetAddress("admin@responderiq05.appspotmail.com", "FirstResponder")); msg.setSubject("Alert!"); msg.setText(" Y=" + d.getinboundVRU1() + "&N=" + d.getinboundVRU2() + // "&3=" + d.getinboundVRU3() + "&A=" + thisAlert.get(0).getalertMsgString()); // send message to all dept members who permit tracking (and sending email alerts) for (Member m : members) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m.getsmsAddress(), m.getfirstName() + "" + m.getlastName())); log.info("Member: " + m.getsmsAddress() + "|" + m.getlastName()); } } // only process for one department - should only be one department break; } } } catch (MessagingException me) { log.info("Error: Messaging"); } catch (IndexOutOfBoundsException mi) { log.info("Error: Out of Bounds"); } // Do not send alert notification if email is a Google Confirmation // if (! sender.toString().contains("mail-noreply@google.com")) { // Transport.send(msg); // } } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { pm.close(); } }
From source file:com.sonicle.webtop.mail.Service.java
public Message createMessage(String from, SimpleMessage smsg, List<JsAttachment> attachments, boolean tosave) throws Exception { MimeMessage msg = null; boolean success = true; String[] to = SimpleMessage.breakAddr(smsg.getTo()); String[] cc = SimpleMessage.breakAddr(smsg.getCc()); String[] bcc = SimpleMessage.breakAddr(smsg.getBcc()); String replyTo = smsg.getReplyTo(); msg = new MimeMessage(mainAccount.getMailSession()); msg.setFrom(getInternetAddress(from)); InternetAddress ia = null;//from w w w .j a v a2 s . c o m //set the TO recipient for (int q = 0; q < to.length; q++) { // Service.logger.debug("to["+q+"]="+to[q]); to[q] = to[q].replace(',', ' '); try { ia = getInternetAddress(to[q]); } catch (AddressException exc) { throw new AddressException(to[q]); } msg.addRecipient(Message.RecipientType.TO, ia); } //set the CC recipient for (int q = 0; q < cc.length; q++) { cc[q] = cc[q].replace(',', ' '); try { ia = getInternetAddress(cc[q]); } catch (AddressException exc) { throw new AddressException(cc[q]); } msg.addRecipient(Message.RecipientType.CC, ia); } //set BCC recipients for (int q = 0; q < bcc.length; q++) { bcc[q] = bcc[q].replace(',', ' '); try { ia = getInternetAddress(bcc[q]); } catch (AddressException exc) { throw new AddressException(bcc[q]); } msg.addRecipient(Message.RecipientType.BCC, ia); } //set reply to addr if (replyTo != null && replyTo.length() > 0) { Address[] replyaddr = new Address[1]; replyaddr[0] = getInternetAddress(replyTo); msg.setReplyTo(replyaddr); } //add any header String headerLines[] = smsg.getHeaderLines(); for (int i = 0; i < headerLines.length; ++i) { if (!headerLines[i].startsWith("Sonicle-reply-folder")) { msg.addHeaderLine(headerLines[i]); } } //add reply/references String inreplyto = smsg.getInReplyTo(); String references[] = smsg.getReferences(); String replyfolder = smsg.getReplyFolder(); if (inreplyto != null) { msg.setHeader("In-Reply-To", inreplyto); } if (references != null && references[0] != null) { msg.setHeader("References", references[0]); } if (tosave) { if (replyfolder != null) { msg.setHeader("Sonicle-reply-folder", replyfolder); } msg.setHeader("Sonicle-draft", "true"); } //add forward data String forwardedfrom = smsg.getForwardedFrom(); String forwardedfolder = smsg.getForwardedFolder(); if (forwardedfrom != null) { msg.setHeader("Forwarded-From", forwardedfrom); } if (tosave) { if (forwardedfolder != null) { msg.setHeader("Sonicle-forwarded-folder", forwardedfolder); } msg.setHeader("Sonicle-draft", "true"); } //set the subject String subject = smsg.getSubject(); try { //subject=MimeUtility.encodeText(smsg.getSubject(), "ISO-8859-1", null); subject = MimeUtility.encodeText(smsg.getSubject()); } catch (Exception exc) { } msg.setSubject(subject); //set priority int priority = smsg.getPriority(); if (priority != 3) { msg.setHeader("X-Priority", "" + priority); //set receipt } String receiptTo = from; try { receiptTo = MimeUtility.encodeText(from, "ISO-8859-1", null); } catch (Exception exc) { } if (smsg.getReceipt()) { msg.setHeader("Disposition-Notification-To", from); //see if there are any new attachments for the message } int noAttach; int newAttach; if (attachments == null) { newAttach = 0; } else { newAttach = attachments.size(); } //get the array of the old attachments Part[] oldParts = smsg.getAttachments(); //check if there are old attachments if (oldParts == null) { noAttach = 0; } else { //old attachments exist noAttach = oldParts.length; } if ((newAttach > 0) || (noAttach > 0) || !smsg.getMime().equalsIgnoreCase("text/plain")) { // create the main Multipart MimeMultipart mp = new MimeMultipart("mixed"); MimeMultipart unrelated = null; String textcontent = smsg.getTextContent(); //if is text, or no alternative text is available, add the content as one single body part //else create a multipart/alternative with both rich and text mime content if (textcontent == null || smsg.getMime().equalsIgnoreCase("text/plain")) { MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8")); mp.addBodyPart(mbp1); } else { MimeMultipart alternative = new MimeMultipart("alternative"); //the rich part MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8")); //the text part MimeBodyPart mbp1 = new MimeBodyPart(); /* ByteArrayOutputStream bos=new ByteArrayOutputStream(textcontent.length()); com.sun.mail.util.QPEncoderStream qpe=new com.sun.mail.util.QPEncoderStream(bos); for(int i=0;i<textcontent.length();++i) { try { qpe.write(textcontent.charAt(i)); } catch(IOException exc) { Service.logger.error("Exception",exc); } } textcontent=new String(bos.toByteArray());*/ mbp1.setContent(textcontent, MailUtils.buildPartContentType("text/plain", "UTF-8")); // mbp1.setHeader("Content-transfer-encoding","quoted-printable"); alternative.addBodyPart(mbp1); alternative.addBodyPart(mbp2); MimeBodyPart altbody = new MimeBodyPart(); altbody.setContent(alternative); mp.addBodyPart(altbody); } if (noAttach > 0) { //if there are old attachments // create the parts with the attachments //MimeBodyPart[] mbps2 = new MimeBodyPart[noAttach]; //Part[] mbps2 = new Part[noAttach]; //for(int e = 0;e < noAttach;e++) { // mbps2[e] = (Part)oldParts[e]; //}//end for e //add the old attachment parts for (int r = 0; r < noAttach; r++) { Object content = null; String contentType = null; String contentFileName = null; if (oldParts[r] instanceof Message) { // Service.logger.debug("Attachment is a message"); Message msgpart = (Message) oldParts[r]; MimeMessage mm = new MimeMessage(mainAccount.getMailSession()); mm.addFrom(msgpart.getFrom()); mm.setRecipients(Message.RecipientType.TO, msgpart.getRecipients(Message.RecipientType.TO)); mm.setRecipients(Message.RecipientType.CC, msgpart.getRecipients(Message.RecipientType.CC)); mm.setRecipients(Message.RecipientType.BCC, msgpart.getRecipients(Message.RecipientType.BCC)); mm.setReplyTo(msgpart.getReplyTo()); mm.setSentDate(msgpart.getSentDate()); mm.setSubject(msgpart.getSubject()); mm.setContent(msgpart.getContent(), msgpart.getContentType()); content = mm; contentType = "message/rfc822"; } else { // Service.logger.debug("Attachment is not a message"); content = oldParts[r].getContent(); if (!(content instanceof MimeMultipart)) { contentType = oldParts[r].getContentType(); contentFileName = oldParts[r].getFileName(); } } MimeBodyPart mbp = new MimeBodyPart(); if (contentFileName != null) { mbp.setFileName(contentFileName); // Service.logger.debug("adding attachment mime "+contentType+" filename "+contentFileName); contentType += "; name=\"" + contentFileName + "\""; } if (content instanceof MimeMultipart) mbp.setContent((MimeMultipart) content); else mbp.setDataHandler(new DataHandler(content, contentType)); mp.addBodyPart(mbp); } } //end if, adding old attachments if (newAttach > 0) { //if there are new attachments // create the parts with the attachments MimeBodyPart[] mbps = new MimeBodyPart[newAttach]; for (int e = 0; e < newAttach; e++) { mbps[e] = new MimeBodyPart(); // attach the file to the message JsAttachment attach = (JsAttachment) attachments.get(e); UploadedFile upfile = getUploadedFile(attach.uploadId); FileDataSource fds = new FileDataSource(upfile.getFile()); mbps[e].setDataHandler(new DataHandler(fds)); // filename starts has format: // "_" + userid + sessionId + "_" + filename // if (attach.inline) { mbps[e].setDisposition(Part.INLINE); } String contentFileName = attach.fileName.trim(); mbps[e].setFileName(contentFileName); String contentType = upfile.getMediaType() + "; name=\"" + contentFileName + "\""; mbps[e].setHeader("Content-type", contentType); if (attach.cid != null && attach.cid.trim().length() > 0) { mbps[e].setHeader("Content-ID", "<" + attach.cid + ">"); mbps[e].setHeader("X-Attachment-Id", attach.cid); mbps[e].setDisposition(Part.INLINE); if (unrelated == null) unrelated = new MimeMultipart("mixed"); } } //end for e //add the new attachment parts if (unrelated == null) { for (int r = 0; r < newAttach; r++) mp.addBodyPart(mbps[r]); } else { //mp becomes the related part with text parts and cids MimeMultipart related = mp; related.setSubType("related"); //nest the related part into the mixed part mp = unrelated; MimeBodyPart mbd = new MimeBodyPart(); mbd.setContent(related); mp.addBodyPart(mbd); for (int r = 0; r < newAttach; r++) { if (mbps[r].getHeader("Content-ID") != null) { related.addBodyPart(mbps[r]); } else { mp.addBodyPart(mbps[r]); } } } } //end if, adding new attachments // // msg.addHeaderLine("This is a multi-part message in MIME format."); // add the Multipart to the message msg.setContent(mp); } else { //end if newattach msg.setText(smsg.getContent()); } //singlepart message msg.setSentDate(new java.util.Date()); return msg; }