List of usage examples for javax.mail.internet MimeMessage setSubject
public void setSubject(String subject, String charset) throws MessagingException
From source file:org.fireflow.service.email.send.MailSenderImpl.java
/** * TODO ?//ww w . j a v a 2s .c o m * @param mailSession * @param mailMessage * @return * @throws MessagingException * @throws AddressException * @throws ServiceInvocationException */ private MimeMessage createMimeMessage(Session mailSession, MailMessage mailMessage) throws AddressException, MessagingException { MimeMessage mimeMsg = new MimeMessage(mailSession); //1?set from //Assert.notNull(mailMessage.getFrom(),"From address must not be null"); mimeMsg.setFrom(new InternetAddress(mailMessage.getFrom())); //2?set mailto List<String> mailToList = mailMessage.getMailToList(); InternetAddress[] addressList = new InternetAddress[mailToList.size()]; for (int i = 0; i < mailToList.size(); i++) { String mailTo = mailToList.get(i); addressList[i] = new InternetAddress(mailTo); } mimeMsg.setRecipients(Message.RecipientType.TO, addressList); //3?set cc List<String> ccList = mailMessage.getCarbonCopyList(); if (ccList != null && ccList.size() > 0) { addressList = new InternetAddress[ccList.size()]; for (int i = 0; i < ccList.size(); i++) { String mailTo = ccList.get(i); addressList[i] = new InternetAddress(mailTo); } mimeMsg.setRecipients(Message.RecipientType.CC, addressList); } //4?set subject mimeMsg.setSubject(mailMessage.getSubject(), mailServiceDef.getCharset()); //5?set sentDate if (this.sentDate != null) { mimeMsg.setSentDate(sentDate); } //6?set email body Multipart multiPart = new MimeMultipart(); MimeBodyPart bp = new MimeBodyPart(); if (mailMessage.getBodyIsHtml()) bp.setContent(mailMessage.getBody(), CONTENT_TYPE_HTML + CONTENT_TYPE_CHARSET_SUFFIX + mailServiceDef.getCharset()); else bp.setText(mailMessage.getBody(), mailServiceDef.getCharset()); multiPart.addBodyPart(bp); mimeMsg.setContent(multiPart); //7?set attachment //TODO ? return mimeMsg; }
From source file:edu.harvard.iq.dataverse.MailServiceBean.java
public boolean sendSystemEmail(String to, String subject, String messageText) { boolean sent = false; String rootDataverseName = dataverseService.findRootDataverse().getName(); String body = messageText + BundleUtil.getStringFromBundle("notification.email.closing", Arrays.asList(BrandingUtil.getInstallationBrandName(rootDataverseName))); logger.fine("Sending email to " + to + ". Subject: <<<" + subject + ">>>. Body: " + body); try {//from w w w . j ava2s . c o m MimeMessage msg = new MimeMessage(session); InternetAddress systemAddress = getSystemAddress(); if (systemAddress != null) { msg.setFrom(systemAddress); msg.setSentDate(new Date()); String[] recipientStrings = to.split(","); InternetAddress[] recipients = new InternetAddress[recipientStrings.length]; for (int i = 0; i < recipients.length; i++) { try { recipients[i] = new InternetAddress('"' + recipientStrings[i] + '"', "", charset); } catch (UnsupportedEncodingException ex) { logger.severe(ex.getMessage()); } } msg.setRecipients(Message.RecipientType.TO, recipients); msg.setSubject(subject, charset); msg.setText(body, charset); try { Transport.send(msg, recipients); sent = true; } catch (SMTPSendFailedException ssfe) { logger.warning("Failed to send mail to " + to + " (SMTPSendFailedException)"); } } else { logger.fine("Skipping sending mail to " + to + ", because the \"no-reply\" address not set (" + Key.SystemEmail + " setting)."); } } catch (AddressException ae) { logger.warning("Failed to send mail to " + to); ae.printStackTrace(System.out); } catch (MessagingException me) { logger.warning("Failed to send mail to " + to); me.printStackTrace(System.out); } return sent; }
From source file:org.eclipse.che.mail.MailSender.java
public void sendMail(EmailBean emailBean) throws SendMailException { File tempDir = null;//from w ww.j ava 2 s .c om try { MimeMessage message = new MimeMessage(mailSessionProvider.get()); Multipart contentPart = new MimeMultipart(); MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(emailBean.getBody(), "UTF-8", getSubType(emailBean.getMimeType())); contentPart.addBodyPart(bodyPart); if (emailBean.getAttachments() != null) { tempDir = Files.createTempDir(); for (Attachment attachment : emailBean.getAttachments()) { // Create attachment file in temporary directory byte[] attachmentContent = Base64.getDecoder().decode(attachment.getContent()); File attachmentFile = new File(tempDir, attachment.getFileName()); Files.write(attachmentContent, attachmentFile); // Attach the attachment file to email MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.attachFile(attachmentFile); attachmentPart.setContentID("<" + attachment.getContentId() + ">"); contentPart.addBodyPart(attachmentPart); } } message.setContent(contentPart); message.setSubject(emailBean.getSubject(), "UTF-8"); message.setFrom(new InternetAddress(emailBean.getFrom(), true)); message.setSentDate(new Date()); message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(emailBean.getTo())); if (emailBean.getReplyTo() != null) { message.setReplyTo(InternetAddress.parse(emailBean.getReplyTo())); } LOG.info("Sending from {} to {} with subject {}", emailBean.getFrom(), emailBean.getTo(), emailBean.getSubject()); Transport.send(message); LOG.debug("Mail sent"); } catch (Exception e) { LOG.error(e.getLocalizedMessage()); throw new SendMailException(e.getLocalizedMessage(), e); } finally { if (tempDir != null) { try { FileUtils.deleteDirectory(tempDir); } catch (IOException exception) { LOG.error(exception.getMessage()); } } } }
From source file:org.linagora.linshare.core.service.impl.MailNotifierServiceImpl.java
@Override public void sendNotification(String smtpSender, String replyTo, String recipient, String subject, String htmlContent, String inReplyTo, String references) throws SendFailedException { if (smtpServer.equals("")) { logger.warn("Mail notifications are disabled."); return;// ww w .ja va 2s .c om } // get the mail session Session session = getMailSession(); // Define message MimeMessage messageMim = new MimeMessage(session); try { messageMim.setFrom(new InternetAddress(smtpSender)); if (replyTo != null) { InternetAddress reply[] = new InternetAddress[1]; reply[0] = new InternetAddress(replyTo); messageMim.setReplyTo(reply); } messageMim.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient)); if (inReplyTo != null && inReplyTo != "") { // This field should contain only ASCCI character (RFC 822) if (isPureAscii(inReplyTo)) { messageMim.setHeader("In-Reply-To", inReplyTo); } } if (references != null && references != "") { // This field should contain only ASCCI character (RFC 822) if (isPureAscii(references)) { messageMim.setHeader("References", references); } } messageMim.setSubject(subject, charset); // Create a "related" Multipart message // content type is multipart/alternative // it will contain two part BodyPart 1 and 2 Multipart mp = new MimeMultipart("alternative"); // BodyPart 2 // content type is multipart/related // A multipart/related is used to indicate that message parts should // not be considered individually but rather // as parts of an aggregate whole. The message consists of a root // part (by default, the first) which reference other parts inline, // which may in turn reference other parts. Multipart html_mp = new MimeMultipart("related"); // Include an HTML message with images. // BodyParts: the HTML file and an image // Get the HTML file BodyPart rel_bph = new MimeBodyPart(); rel_bph.setDataHandler( new DataHandler(new ByteArrayDataSource(htmlContent, "text/html; charset=" + charset))); html_mp.addBodyPart(rel_bph); // Create the second BodyPart of the multipart/alternative, // set its content to the html multipart, and add the // second bodypart to the main multipart. BodyPart alt_bp2 = new MimeBodyPart(); alt_bp2.setContent(html_mp); mp.addBodyPart(alt_bp2); messageMim.setContent(mp); // RFC 822 "Date" header field // Indicates that the message is complete and ready for delivery messageMim.setSentDate(new GregorianCalendar().getTime()); // Since we used html tags, the content must be marker as text/html // messageMim.setContent(content,"text/html; charset="+charset); Transport tr = session.getTransport("smtp"); // Connect to smtp server, if needed if (needsAuth) { tr.connect(smtpServer, smtpPort, smtpUser, smtpPassword); messageMim.saveChanges(); tr.sendMessage(messageMim, messageMim.getAllRecipients()); tr.close(); } else { // Send message Transport.send(messageMim); } } catch (SendFailedException e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort + " to " + recipient, e); throw e; } catch (MessagingException e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e); throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e); } catch (Exception e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e); throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e); } }
From source file:org.openiam.idm.srvc.msg.service.MailSenderClient.java
public void send(Message msg) { Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.transport.protocol", "smtp"); if (username != null && !username.isEmpty()) { properties.setProperty("mail.user", username); properties.setProperty("mail.password", password); }/*from w ww. j a v a2s. co m*/ if (port != null && !port.isEmpty()) { properties.setProperty("mail.smtp.port", port); } Session session = Session.getDefaultInstance(properties); MimeMessage message = new MimeMessage(session); try { message.setFrom(msg.getFrom()); if (msg.getTo().size() > 1) { List<InternetAddress> addresses = msg.getTo(); message.addRecipients(TO, addresses.toArray(new Address[addresses.size()])); } else { message.addRecipient(TO, msg.getTo().get(0)); } if (msg.getBcc() != null && msg.getBcc().size() != 0) { if (msg.getTo().size() > 1) { List<InternetAddress> addresses = msg.getBcc(); message.addRecipients(BCC, addresses.toArray(new Address[addresses.size()])); } else { message.addRecipient(TO, msg.getBcc().get(0)); } } if (msg.getCc() != null && msg.getCc().size() > 0) { if (msg.getCc().size() > 1) { List<InternetAddress> addresses = msg.getCc(); message.addRecipients(CC, addresses.toArray(new Address[addresses.size()])); } else { message.addRecipient(CC, msg.getCc().get(0)); } } message.setSubject(msg.getSubject(), "UTF-8"); MimeBodyPart mbp1 = new MimeBodyPart(); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); if (msg.getBodyType() == Message.BodyType.HTML_TEXT) { mbp1.setContent(msg.getBody(), "text/html"); } else { mbp1.setText(msg.getBody(), "UTF-8"); } if (port != null && !port.isEmpty()) { properties.setProperty("mail.smtp.port", port); } mp.addBodyPart(mbp1); if (msg.getAttachments().size() > 0) { for (String fileName : msg.getAttachments()) { // create the second message part MimeBodyPart mbpFile = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(fileName); mbpFile.setDataHandler(new DataHandler(fds)); mbpFile.setFileName(fds.getName()); mp.addBodyPart(mbpFile); } } // add the Multipart to the message message.setContent(mp); if (username != null && !username.isEmpty()) { properties.setProperty("mail.user", username); properties.setProperty("mail.password", password); properties.put("mail.smtp.auth", auth); properties.put("mail.smtp.starttls.enable", starttls); Transport mailTransport = session.getTransport(); mailTransport.connect(host, username, password); mailTransport.sendMessage(message, message.getAllRecipients()); } else { Transport.send(message); log.debug("Message successfully sent."); } } catch (Throwable e) { log.error("Exception while sending mail", e); } }
From source file:org.nuxeo.ecm.platform.ec.notification.email.EmailHelper.java
protected void sendmail0(Map<String, Object> mail) throws MessagingException, IOException, TemplateException, LoginException, RenderingException { Session session = getSession();//from w w w . j a v a 2 s. c om if (javaMailNotAvailable || session == null) { log.warn("Not sending email since JavaMail is not configured"); return; } // Construct a MimeMessage MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(session.getProperty("mail.from"))); Object to = mail.get("mail.to"); if (!(to instanceof String)) { log.error("Invalid email recipient: " + to); return; } msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String) to, false)); RenderingService rs = Framework.getService(RenderingService.class); DocumentRenderingContext context = new DocumentRenderingContext(); context.remove("doc"); context.putAll(mail); context.setDocument((DocumentModel) mail.get("document")); context.put("Runtime", Framework.getRuntime()); String customSubjectTemplate = (String) mail.get(NotificationConstants.SUBJECT_TEMPLATE_KEY); if (customSubjectTemplate == null) { String subjTemplate = (String) mail.get(NotificationConstants.SUBJECT_KEY); Template templ = new Template("name", new StringReader(subjTemplate), stringCfg); Writer out = new StringWriter(); templ.process(mail, out); out.flush(); msg.setSubject(out.toString(), "UTF-8"); } else { rs.registerEngine(new NotificationsRenderingEngine(customSubjectTemplate)); LoginContext lc = Framework.login(); Collection<RenderingResult> results = rs.process(context); String subjectMail = "<HTML><P>No parsing Succeded !!!</P></HTML>"; for (RenderingResult result : results) { subjectMail = (String) result.getOutcome(); } subjectMail = NotificationServiceHelper.getNotificationService().getEMailSubjectPrefix() + subjectMail; msg.setSubject(subjectMail, "UTF-8"); lc.logout(); } msg.setSentDate(new Date()); rs.registerEngine(new NotificationsRenderingEngine((String) mail.get(NotificationConstants.TEMPLATE_KEY))); LoginContext lc = Framework.login(); Collection<RenderingResult> results = rs.process(context); String bodyMail = "<HTML><P>No parsing Succedeed !!!</P></HTML>"; for (RenderingResult result : results) { bodyMail = (String) result.getOutcome(); } lc.logout(); rs.unregisterEngine("ftl"); msg.setContent(bodyMail, "text/html; charset=utf-8"); // Send the message. Transport.send(msg); }
From source file:org.pentaho.platform.plugin.action.builtin.EmailComponent.java
@Override public boolean executeAction() { EmailAction emailAction = (EmailAction) getActionDefinition(); String messagePlain = emailAction.getMessagePlain().getStringValue(); String messageHtml = emailAction.getMessageHtml().getStringValue(); String subject = emailAction.getSubject().getStringValue(); String to = emailAction.getTo().getStringValue(); String cc = emailAction.getCc().getStringValue(); String bcc = emailAction.getBcc().getStringValue(); String from = emailAction.getFrom().getStringValue(defaultFrom); if (from.trim().length() == 0) { from = defaultFrom;//from ww w. j a va 2 s. c om } /* * if( context.getInputNames().contains( "attach" ) ) { //$NON-NLS-1$ Object attachParameter = * context.getInputParameter( "attach" ).getValue(); //$NON-NLS-1$ // We have a list of attachments, each element of * the list is the name of the parameter containing the attachment // Use the parameter filename portion as the * attachment name. if ( attachParameter instanceof String ) { String attachName = context.getInputParameter( * "attach-name" ).getStringValue(); //$NON-NLS-1$ AttachStruct attachData = getAttachData( context, * (String)attachParameter, attachName ); if ( attachData != null ) { attachments.add( attachData ); } } else if ( * attachParameter instanceof List ) { for ( int i = 0; i < ((List)attachParameter).size(); ++i ) { AttachStruct * attachData = getAttachData( context, ((List)attachParameter).get( i ).toString(), null ); if ( attachData != null * ) { attachments.add( attachData ); } } } else if ( attachParameter instanceof Map ) { for ( Iterator it = * ((Map)attachParameter).entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next(); * AttachStruct attachData = getAttachData( context, (String)entry.getValue(), (String)entry.getKey() ); if ( * attachData != null ) { attachments.add( attachData ); } } } } * * int maxSize = Integer.MAX_VALUE; try { maxSize = new Integer( props.getProperty( "mail.max.attach.size" ) * ).intValue(); } catch( Throwable t ) { //ignore if not set to a valid value } * * if ( totalAttachLength > maxSize ) { // Sort them in order TreeMap tm = new TreeMap(); for( int idx=0; * idx<attachments.size(); idx++ ) { // tm.put( new Integer( )) } } */ if (ComponentBase.debug) { debug(Messages.getInstance().getString("Email.DEBUG_TO_FROM", to, from)); //$NON-NLS-1$ debug(Messages.getInstance().getString("Email.DEBUG_CC_BCC", cc, bcc)); //$NON-NLS-1$ debug(Messages.getInstance().getString("Email.DEBUG_SUBJECT", subject)); //$NON-NLS-1$ debug(Messages.getInstance().getString("Email.DEBUG_PLAIN_MESSAGE", messagePlain)); //$NON-NLS-1$ debug(Messages.getInstance().getString("Email.DEBUG_HTML_MESSAGE", messageHtml)); //$NON-NLS-1$ } if ((to == null) || (to.trim().length() == 0)) { // Get the output stream that the feedback is going into OutputStream feedbackStream = getFeedbackOutputStream(); if (feedbackStream != null) { createFeedbackParameter("to", Messages.getInstance().getString("Email.USER_ENTER_EMAIL_ADDRESS"), //$NON-NLS-1$//$NON-NLS-2$ "", "", true); //$NON-NLS-1$ //$NON-NLS-2$ setFeedbackMimeType("text/html"); //$NON-NLS-1$ return true; } else { return false; } } if (subject == null) { error(Messages.getInstance().getErrorString("Email.ERROR_0005_NULL_SUBJECT", getActionName())); //$NON-NLS-1$ return false; } if ((messagePlain == null) && (messageHtml == null)) { error(Messages.getInstance().getErrorString("Email.ERROR_0006_NULL_BODY", getActionName())); //$NON-NLS-1$ return false; } if (getRuntimeContext().isPromptPending()) { return true; } try { Properties props = new Properties(); final IEmailService service = PentahoSystem.get(IEmailService.class, "IEmailService", PentahoSessionHolder.getSession()); props.put("mail.smtp.host", service.getEmailConfig().getSmtpHost()); props.put("mail.smtp.port", ObjectUtils.toString(service.getEmailConfig().getSmtpPort())); props.put("mail.transport.protocol", service.getEmailConfig().getSmtpProtocol()); props.put("mail.smtp.starttls.enable", ObjectUtils.toString(service.getEmailConfig().isUseStartTls())); props.put("mail.smtp.auth", ObjectUtils.toString(service.getEmailConfig().isAuthenticate())); props.put("mail.smtp.ssl", ObjectUtils.toString(service.getEmailConfig().isUseSsl())); props.put("mail.smtp.quitwait", ObjectUtils.toString(service.getEmailConfig().isSmtpQuitWait())); props.put("mail.from.default", service.getEmailConfig().getDefaultFrom()); String fromName = service.getEmailConfig().getFromName(); if (StringUtils.isEmpty(fromName)) { fromName = Messages.getInstance().getString("schedulerEmailFromName"); } props.put("mail.from.name", fromName); props.put("mail.debug", ObjectUtils.toString(service.getEmailConfig().isDebug())); Session session; if (service.getEmailConfig().isAuthenticate()) { props.put("mail.userid", service.getEmailConfig().getUserId()); props.put("mail.password", service.getEmailConfig().getPassword()); Authenticator authenticator = new EmailAuthenticator(); session = Session.getInstance(props, authenticator); } else { session = Session.getInstance(props); } // debugging is on if either component (xaction) or email config debug is on if (service.getEmailConfig().isDebug() || ComponentBase.debug) { session.setDebug(true); } // construct the message MimeMessage msg = new MimeMessage(session); if (from != null) { msg.setFrom(new InternetAddress(from)); } else { // There should be no way to get here error(Messages.getInstance().getString("Email.ERROR_0012_FROM_NOT_DEFINED")); //$NON-NLS-1$ } if ((to != null) && (to.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); } if ((cc != null) && (cc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); } if ((bcc != null) && (bcc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); } if (subject != null) { msg.setSubject(subject, LocaleHelper.getSystemEncoding()); } EmailAttachment[] emailAttachments = emailAction.getAttachments(); if ((messagePlain != null) && (messageHtml == null) && (emailAttachments.length == 0)) { msg.setText(messagePlain, LocaleHelper.getSystemEncoding()); } else if (emailAttachments.length == 0) { if (messagePlain != null) { msg.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ } if (messageHtml != null) { msg.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ } } else { // need to create a multi-part message... // create the Multipart and add its parts to it Multipart multipart = new MimeMultipart(); // create and fill the first message part if (messageHtml != null) { // create and fill the first message part MimeBodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ multipart.addBodyPart(htmlBodyPart); } if (messagePlain != null) { MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ multipart.addBodyPart(textBodyPart); } for (EmailAttachment element : emailAttachments) { IPentahoStreamSource source = element.getContent(); if (source == null) { error(Messages.getInstance().getErrorString("Email.ERROR_0015_ATTACHMENT_FAILED")); //$NON-NLS-1$ return false; } DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source); String attachmentName = element.getName(); if (ComponentBase.debug) { debug(Messages.getInstance().getString("Email.DEBUG_ADDING_ATTACHMENT", attachmentName)); //$NON-NLS-1$ } // create the second message part MimeBodyPart attachmentBodyPart = new MimeBodyPart(); // attach the file to the message attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(attachmentName); if (ComponentBase.debug) { debug(Messages.getInstance().getString("Email.DEBUG_ATTACHMENT_SOURCE", //$NON-NLS-1$ dataSource.getName())); } multipart.addBodyPart(attachmentBodyPart); } // add the Multipart to the message msg.setContent(multipart); } msg.setHeader("X-Mailer", EmailComponent.MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); if (ComponentBase.debug) { debug(Messages.getInstance().getString("Email.DEBUG_EMAIL_SUCCESS")); //$NON-NLS-1$ } return true; // TODO: persist the content set for a while... } catch (SendFailedException e) { error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$ /* * Exception ne; MessagingException sfe = e; while ((ne = sfe.getNextException()) != null && ne instanceof * MessagingException) { sfe = (MessagingException) ne; * error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", sfe.toString()), sfe); * //$NON-NLS-1$ } */ } catch (AuthenticationFailedException e) { error(Messages.getInstance().getString("Email.ERROR_0014_AUTHENTICATION_FAILED", to), e); //$NON-NLS-1$ } catch (Throwable e) { error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$ } return false; }
From source file:org.igov.io.mail.Mail.java
public void sendOld() throws EmailException { LOG.info("init"); try {/*from w ww.j a v a2 s . c o m*/ MultiPartEmail oMultiPartEmail = new MultiPartEmail(); LOG.info("(getHost()={})", getHost()); oMultiPartEmail.setHostName(getHost()); String[] asTo = { sMailOnly(getTo()) }; if (getTo().contains("\\,")) { asTo = getTo().split("\\,");//sTo for (String s : asTo) { LOG.info("oMultiPartEmail.addTo (s={})", s); oMultiPartEmail.addTo(s, "receiver"); } } LOG.info("(getFrom()={})", getFrom()); LOG_BIG.debug("(getFrom()={})", getFrom()); oMultiPartEmail.setFrom(getFrom(), getFrom());//"iGov" oMultiPartEmail.setSubject(getHead()); LOG.info("getHead()={}", getHead()); String sLogin = getAuthUser(); if (sLogin != null && !"".equals(sLogin.trim())) { oMultiPartEmail.setAuthentication(sLogin, getAuthPassword()); LOG.info("withAuth"); } else { LOG.info("withoutAuth"); } //oMultiPartEmail.setAuthentication(getAuthUser(), getAuthPassword()); LOG.info("(getAuthUser()={})", getAuthUser()); //LOG.info("getAuthPassword()=" + getAuthPassword()); oMultiPartEmail.setSmtpPort(getPort()); LOG.info("(getPort()={})", getPort()); oMultiPartEmail.setSSL(isSSL()); LOG.info("(isSSL()={})", isSSL()); oMultiPartEmail.setTLS(isTLS()); LOG.info("(isTLS()={})", isTLS()); oSession = oMultiPartEmail.getMailSession(); MimeMessage oMimeMessage = new MimeMessage(oSession); //oMimeMessage.setFrom(new InternetAddress(getFrom(), "iGov", DEFAULT_ENCODING)); oMimeMessage.setFrom(new InternetAddress(getFrom(), getFrom())); //oMimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(sTo, sToName, DEFAULT_ENCODING)); String sReceiverName = "receiver"; if (asTo.length == 1) { sReceiverName = getToName(); } for (String s : asTo) { LOG.info("oMimeMessage.addRecipient (s={})", s); //oMultiPartEmail.addTo(s, "receiver"); oMimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(s, sReceiverName, DEFAULT_ENCODING)); } //oMimeMessage.addRecipient(Message.RecipientType.TO, // new InternetAddress(sTo, "recipient", DEFAULT_ENCODING)); //new InternetAddress(getTo(), "recipient", DEFAULT_ENCODING)); oMimeMessage.setSubject(getHead(), DEFAULT_ENCODING); _AttachBody(getBody()); //LOG.info("(getBody()={})", getBody()); oMimeMessage.setContent(oMultiparts); // oMimeMessage.getRecipients(Message.RecipientType.CC); //methodCallRunner.registrateMethod(Transport.class.getName(), "send", new Object[]{oMimeMessage}); Transport.send(oMimeMessage); LOG.info("Send " + getTo() + "!!!!!!!!!!!!!!!!!!!!!!!!"); } catch (Exception oException) { LOG.error("FAIL: {} (getTo()={})", oException.getMessage(), getTo()); LOG.trace("FAIL:", oException); throw new EmailException("Error happened when sending email (" + getTo() + ")" + "Exception message: " + oException.getMessage(), oException); } LOG.info("SUCCESS: Sent!"); }
From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java
/** * Send an email based on json payload. Recipient should be present in LDAP directory or in configured whitelist. * * Json sent should have following keys : * * - to : json array of email to send email to ex: ["you@rm.fr", "another-guy@rm.fr"] * - cc : json array of email to 'CC' email ex: ["him@rm.fr"] * - bcc : json array of email to add recipient as blind CC ["secret@rm.fr"] * - subject : subject of email//from w ww . j a va2 s . com * - body : Body of email * * Either 'to', 'cc' or 'bcc' parameter must be present in request. 'subject' and 'body' are mandatory. * * complete json example : * * { * "to": ["you@rm.fr", "another-guy@rm.fr"], * "cc": ["him@rm.fr"], * "bcc": ["secret@rm.fr"], * "subject": "test email", * "body": "Hi, this a test EMail, please do not reply." * } * */ @RequestMapping(value = "/emailProxy", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes = "application/json") @ResponseBody public String emailProxy(@RequestBody String rawRequest, HttpServletRequest request) throws JSONException, MessagingException, UnsupportedEncodingException, DataServiceException { JSONObject payload = new JSONObject(rawRequest); InternetAddress[] to = this.populateRecipient("to", payload); InternetAddress[] cc = this.populateRecipient("cc", payload); InternetAddress[] bcc = this.populateRecipient("bcc", payload); this.checkSubject(payload); this.checkBody(payload); this.checkRecipient(to, cc, bcc); LOG.info("EMail request : user=" + request.getHeader("sec-username") + " to=" + this.extractAddress("to", payload) + " cc=" + this.extractAddress("cc", payload) + " bcc=" + this.extractAddress("bcc", payload) + " roles=" + request.getHeader("sec-roles")); LOG.debug("EMail request : " + payload.toString()); // Instanciate MimeMessage Properties props = System.getProperties(); props.put("mail.smtp.host", this.emailFactory.getSmtpHost()); props.put("mail.protocol.port", this.emailFactory.getSmtpPort()); Session session = Session.getInstance(props, null); MimeMessage message = new MimeMessage(session); // Generate From header InternetAddress from = new InternetAddress(); from.setAddress(this.georConfig.getProperty("emailProxyFromAddress")); from.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname")); message.setFrom(from); // Generate Reply-to header InternetAddress replyTo = new InternetAddress(); replyTo.setAddress(request.getHeader("sec-email")); replyTo.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname")); message.setReplyTo(new Address[] { replyTo }); // Generate to, cc and bcc headers if (to.length > 0) message.setRecipients(Message.RecipientType.TO, to); if (cc.length > 0) message.setRecipients(Message.RecipientType.CC, cc); if (bcc.length > 0) message.setRecipients(Message.RecipientType.BCC, bcc); // Add subject and body message.setSubject(payload.getString("subject"), "UTF-8"); message.setText(payload.getString("body"), "UTF-8", "plain"); message.setSentDate(new Date()); // finally send message Transport.send(message); JSONObject res = new JSONObject(); res.put("success", true); return res.toString(); }
From source file:org.apache.camel.component.mail.MailBinding.java
public void populateMailMessage(MailEndpoint endpoint, MimeMessage mimeMessage, Exchange exchange) throws MessagingException, IOException { // camel message headers takes precedence over endpoint configuration if (hasRecipientHeaders(exchange)) { setRecipientFromCamelMessage(mimeMessage, exchange); } else {/* www . ja va2 s . c o m*/ // fallback to endpoint configuration setRecipientFromEndpointConfiguration(mimeMessage, endpoint); } // must have at least one recipients otherwise we do not know where to send the mail if (mimeMessage.getAllRecipients() == null) { throw new IllegalArgumentException("The mail message does not have any recipients set."); } // set the subject if it was passed in as an option in the uri. Note: if it is in both the URI // and headers the headers win. String subject = endpoint.getConfiguration().getSubject(); if (subject != null) { mimeMessage.setSubject(subject, IOConverter.getCharsetName(exchange, false)); } // append the rest of the headers (no recipients) that could be subject, reply-to etc. appendHeadersFromCamelMessage(mimeMessage, endpoint.getConfiguration(), exchange); if (empty(mimeMessage.getFrom())) { // lets default the address to the endpoint destination String from = endpoint.getConfiguration().getFrom(); mimeMessage.setFrom(new InternetAddress(from)); } // if there is an alternative body provided, set up a mime multipart alternative message if (hasAlternativeBody(endpoint.getConfiguration(), exchange)) { createMultipartAlternativeMessage(mimeMessage, endpoint.getConfiguration(), exchange); } else { if (exchange.getIn().hasAttachments()) { appendAttachmentsFromCamel(mimeMessage, endpoint.getConfiguration(), exchange); } else { populateContentOnMimeMessage(mimeMessage, endpoint.getConfiguration(), exchange); } } }