List of usage examples for javax.mail Multipart addBodyPart
public synchronized void addBodyPart(BodyPart part) throws MessagingException
From source file:org.georchestra.console.ws.emails.EmailController.java
/** * Send EmailEntry to smtp server/* w w w .j av a 2 s . co m*/ * * @param email email to send * @throws NameNotFoundException if recipient cannot be found in LDAP server * @throws DataServiceException if LDAP server is not available * @throws MessagingException if some field of email cannot be encoded (malformed email address) */ private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException { final Session session = Session.getInstance(System.getProperties(), null); session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost()); session.getProperties().setProperty("mail.smtp.port", (new Integer(this.emailFactory.getSmtpPort())).toString()); final MimeMessage message = new MimeMessage(session); Account recipient = this.accountDao.findByUID(email.getRecipient()); InternetAddress[] senders = { new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) }; message.addFrom(senders); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail())); message.setSubject(email.getSubject()); message.setHeader("Date", (new MailDateFormat()).format(email.getDate())); // Mail content Multipart multiPart = new MimeMultipart("alternative"); // attachments for (Attachment att : email.getAttachments()) { MimeBodyPart mbp = new MimeBodyPart(); mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType()))); mbp.setFileName(att.getName()); multiPart.addBodyPart(mbp); } // html part MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(email.getBody(), "text/html; charset=utf-8"); multiPart.addBodyPart(htmlPart); message.setContent(multiPart); // Send message Transport.send(message); }
From source file:com.assetmanager.service.mail.MailService.java
/** * Sends the activation e-mail to the given user. * * @param user the user/*from ww w . j a va2 s . co m*/ * @param locale the locale * @throws MessagingException messaging exception */ public final void sendActivationEmail(final UserAccount user, final String locale) throws MessagingException { final Properties props = new Properties(); final Session session = Session.getDefaultInstance(props, null); final Message message = new MimeMessage(session); final Multipart multipart = new MimeMultipart(); final MimeBodyPart htmlPart = new MimeBodyPart(); final MimeBodyPart textPart = new MimeBodyPart(); message.setFrom(new InternetAddress(getFromAddress())); message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail())); message.setSubject(messageSource.getMessage("mail.subject", null, new Locale(locale))); textPart.setContent(messageSource.getMessage("mail.body.txt", new Object[] { getHostname(), user.getActivationKey() }, new Locale(locale)), "text/plain"); htmlPart.setContent(messageSource.getMessage("mail.body.html", new Object[] { getHostname(), user.getActivationKey() }, new Locale(locale)), "text/html"); multipart.addBodyPart(textPart); multipart.addBodyPart(htmlPart); message.setContent(multipart); Transport.send(message); }
From source file:com.email.SendEmail.java
/** * Sends a single email and uses account based off of the section that the * email comes from after email is sent the attachments are gathered * together and collated into a single PDF file and a history entry is * created based off of that entry/* w ww . j a v a 2 s .c o m*/ * * @param eml EmailOutModel */ public static void sendEmails(EmailOutModel eml) { SystemEmailModel account = null; String section = eml.getSection(); if (eml.getSection().equalsIgnoreCase("Hearings") && (eml.getCaseType().equalsIgnoreCase("MED") || eml.getCaseType().equalsIgnoreCase("REP") || eml.getCaseType().equalsIgnoreCase("ULP"))) { section = eml.getCaseType(); } //Get Account for (SystemEmailModel acc : Global.getSystemEmailParams()) { if (acc.getSection().equals(section)) { account = acc; break; } } //Account Exists? if (account != null) { //Case Location String casePath = (eml.getCaseType().equals("CSC") || eml.getCaseType().equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(eml) : FileService.getCaseFolderLocation(eml); //Attachment List boolean allFilesExists = true; List<EmailOutAttachmentModel> attachmentList = EmailOutAttachment.getAttachmentsByEmail(eml.getId()); for (EmailOutAttachmentModel attach : attachmentList) { File attachment = new File(casePath + attach.getFileName()); boolean exists = attachment.exists(); if (exists == false) { allFilesExists = false; SECExceptionsModel item = new SECExceptionsModel(); item.setClassName("SendEmail"); item.setMethodName("sendEmails"); item.setExceptionType("FileMissing"); item.setExceptionDescription("Can't Send Email, File Missing for EmailID: " + eml.getId() + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator() + "File: " + attachment); ExceptionHandler.HandleNoException(item); break; } else { if ("docx".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName())) || "doc".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName()))) { if (!attachment.renameTo(attachment)) { allFilesExists = false; SECExceptionsModel item = new SECExceptionsModel(); item.setClassName("SendEmail"); item.setMethodName("sendEmails"); item.setExceptionType("File In Use"); item.setExceptionDescription("Can't Send Email, File In Use for EmailID: " + eml.getId() + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator() + "File: " + attachment); ExceptionHandler.HandleNoException(item); break; } } } } if (allFilesExists) { //Set up Initial Merge Utility PDFMergerUtility ut = new PDFMergerUtility(); //List ConversionPDFs To Delete Later List<String> tempPDFList = new ArrayList<>(); //create email message body Date emailSentTime = new Date(); String emailPDFname = EmailBodyToPDF.createEmailOutBody(eml, attachmentList, emailSentTime); //Add Email Body To PDF Merge try { ut.addSource(casePath + emailPDFname); tempPDFList.add(casePath + emailPDFname); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //Get parts String FromAddress = account.getEmailAddress(); String[] TOAddressess = ((eml.getTo() == null) ? "".split(";") : eml.getTo().split(";")); String[] CCAddressess = ((eml.getCc() == null) ? "".split(";") : eml.getCc().split(";")); String[] BCCAddressess = ((eml.getBcc() == null) ? "".split(";") : eml.getBcc().split(";")); String emailSubject = eml.getSubject(); String emailBody = eml.getBody(); //Set Email Parts Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account); Properties properties = EmailProperties.setEmailOutProperties(account); Session session = Session.getInstance(properties, auth); MimeMessage smessage = new MimeMessage(session); Multipart multipart = new MimeMultipart(); //Add Parts to Email Message try { smessage.addFrom(new InternetAddress[] { new InternetAddress(FromAddress) }); for (String To : TOAddressess) { if (EmailValidator.getInstance().isValid(To)) { smessage.addRecipient(Message.RecipientType.TO, new InternetAddress(To)); } } for (String CC : CCAddressess) { if (EmailValidator.getInstance().isValid(CC)) { smessage.addRecipient(Message.RecipientType.CC, new InternetAddress(CC)); } } for (String BCC : BCCAddressess) { if (EmailValidator.getInstance().isValid(BCC)) { smessage.addRecipient(Message.RecipientType.BCC, new InternetAddress(BCC)); } } smessage.setSubject(emailSubject); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(emailBody, "text/plain"); multipart.addBodyPart(messageBodyPart); //get attachments for (EmailOutAttachmentModel attachment : attachmentList) { String fileName = attachment.getFileName(); String extension = FilenameUtils.getExtension(fileName); //Convert attachments to PDF //If Image if (FileService.isImageFormat(fileName)) { fileName = ImageToPDF.createPDFFromImageNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If Word Doc } else if (extension.equals("docx") || extension.equals("doc")) { fileName = WordToPDF.createPDFNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If Text File } else if ("txt".equals(extension)) { fileName = TXTtoPDF.createPDFNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If PDF } else if (FilenameUtils.getExtension(fileName).equals("pdf")) { //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } } DataSource source = new FileDataSource(casePath + fileName); messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); } smessage.setContent(multipart); //Send Message if (Global.isOkToSendEmail()) { Transport.send(smessage); } else { Audit.addAuditEntry("Email Not Actually Sent: " + eml.getId() + " - " + emailSubject); } //DocumentFileName String savedDoc = (String.valueOf(new Date().getTime()) + "_" + eml.getSubject()) .replaceAll("[:\\\\/*?|<>]", "_") + ".pdf"; //Set Merge File Destination ut.setDestinationFileName(casePath + savedDoc); //Try to Merge try { ut.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly()); } catch (IOException ex) { ExceptionHandler.Handle(ex); } //Add emailBody Activity addEmailActivity(eml, savedDoc, emailSentTime); //Copy to related case folders if (section.equals("MED")) { List<RelatedCaseModel> relatedMedList = RelatedCase.getRelatedCases(eml); if (relatedMedList.size() > 0) { for (RelatedCaseModel related : relatedMedList) { //Copy finalized document to proper folder File srcFile = new File(casePath + savedDoc); File destPath = new File((section.equals("CSC") || section.equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(related) : FileService.getCaseFolderLocationRelatedCase(related)); destPath.mkdirs(); try { FileUtils.copyFileToDirectory(srcFile, destPath); } catch (IOException ex) { Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex); } //Add Related Case Activity Entry addEmailActivityRelatedCase(eml, related, savedDoc, emailSentTime); } } } else { //This is blanket and should grab all related cases. (UNTESTED outside of CMDS) List<EmailOutRelatedCaseModel> relatedList = EmailOutRelatedCase.getRelatedCases(eml); if (relatedList.size() > 0) { for (EmailOutRelatedCaseModel related : relatedList) { //Copy finalized document to proper folder File srcFile = new File(casePath + savedDoc); File destPath = new File((section.equals("CSC") || section.equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(related) : FileService.getCaseFolderLocationEmailOutRelatedCase(related)); destPath.mkdirs(); try { FileUtils.copyFileToDirectory(srcFile, destPath); } catch (IOException ex) { Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex); } //Add Related Case Activity Entry addEmailOutActivityRelatedCase(eml, related, savedDoc, emailSentTime); } } } //Clean SQL entries EmailOut.deleteEmailEntry(eml.getId()); EmailOutAttachment.deleteAttachmentsForEmail(eml.getId()); EmailOutRelatedCase.deleteEmailOutRelatedForEmail(eml.getId()); //Clean up temp PDFs for (String tempPDF : tempPDFList) { new File(tempPDF).delete(); } } catch (AddressException ex) { ExceptionHandler.Handle(ex); } catch (MessagingException ex) { ExceptionHandler.Handle(ex); } } } }
From source file:com.threewks.thundr.mail.JavaMailMailer.java
private void addAttachments(Multipart multipart, List<Attachment> attachments) throws MessagingException { for (Attachment attachment : attachments) { BasicViewRenderer response = render(attachment.view()); byte[] base64Encoded = Base64.encodeToByte(response.getOutputAsBytes()); InternetHeaders headers = new InternetHeaders(); headers.addHeader(Header.ContentType, response.getContentType()); headers.addHeader(Header.ContentTransferEncoding, "base64"); MimeBodyPart part = new MimeBodyPart(headers, base64Encoded); part.setFileName(attachment.name()); part.setDisposition(attachment.disposition().value()); if (attachment.isInline()) { part.setContentID(attachment.contentId()); }//from ww w . j a v a 2 s. c om multipart.addBodyPart(part); } }
From source file:com.ikon.util.MailUtils.java
/** * Create a mail./*from ww w . j a va 2 s. c o m*/ * * @param fromAddress Origin address. * @param toAddress Destination addresses. * @param subject The mail subject. * @param text The mail body. * @throws MessagingException If there is any error. */ private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text, Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath }); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (fromAddress != null) { InternetAddress from = new InternetAddress(fromAddress); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[toAddress.size()]; int idx = 0; for (Iterator<String> it = toAddress.iterator(); it.hasNext();) { to[idx++] = new InternetAddress(it.next()); } // Build a multiparted mail with HTML and text content for better SPAM behaviour Multipart content = new MimeMultipart(); // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(text); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8"); htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); idx = 0; if (docsPath != null) { for (String docPath : docsPath) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(docPath); try { final Document doc = OKMDocument.getInstance().getProperties(null, docPath); is = OKMDocument.getInstance().getContent(null, docPath, false); final File tmpAttch = tmpAttachments.get(idx++); fos = new FileOutputStream(tmpAttch); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmpAttch.getPath()) { public String getContentType() { return doc.getMimeType(); } }; docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(MimeUtility.encodeText(docName)); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(subject, "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }
From source file:nl.nn.adapterframework.senders.MailSender.java
protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType, String messageBase64, String charset, Collection recipients, Collection attachments) throws SenderException { StringBuffer sb = new StringBuffer(); if (recipients == null || recipients.size() == 0) { throw new SenderException("MailSender [" + getName() + "] has no recipients for message"); }/* w w w. ja v a 2 s .co m*/ if (StringUtils.isEmpty(from)) { from = defaultFrom; } if (StringUtils.isEmpty(subject)) { subject = defaultSubject; } log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject + "] to #recipients [" + recipients.size() + "]"); if (StringUtils.isEmpty(messageType)) { messageType = defaultMessageType; } if (StringUtils.isEmpty(messageBase64)) { messageBase64 = defaultMessageBase64; } try { if (log.isDebugEnabled()) { sb.append("MailSender [" + getName() + "] sending message "); sb.append("[smtpHost=" + smtpHost); sb.append("[from=" + from + "]"); sb.append("[subject=" + subject + "]"); sb.append("[threadTopic=" + threadTopic + "]"); sb.append("[text=" + message + "]"); sb.append("[type=" + messageType + "]"); sb.append("[base64=" + messageBase64 + "]"); } if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) { message = decodeBase64ToString(message); } // construct a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setSubject(subject, charset); if (StringUtils.isNotEmpty(threadTopic)) { msg.setHeader("Thread-Topic", threadTopic); } Iterator iter = recipients.iterator(); boolean recipientsFound = false; while (iter.hasNext()) { Element recipientElement = (Element) iter.next(); String recipient = XmlUtils.getStringValue(recipientElement); if (StringUtils.isNotEmpty(recipient)) { String typeAttr = recipientElement.getAttribute("type"); Message.RecipientType recipientType = Message.RecipientType.TO; if ("cc".equalsIgnoreCase(typeAttr)) { recipientType = Message.RecipientType.CC; } if ("bcc".equalsIgnoreCase(typeAttr)) { recipientType = Message.RecipientType.BCC; } msg.addRecipient(recipientType, new InternetAddress(recipient)); recipientsFound = true; if (log.isDebugEnabled()) { sb.append("[recipient(" + typeAttr + ")=" + recipient + "]"); } } else { log.debug("empty recipient found, ignoring"); } } if (!recipientsFound) { throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients"); } String messageTypeWithCharset; if (charset == null) { charset = System.getProperty("mail.mime.charset"); if (charset == null) { charset = System.getProperty("file.encoding"); } } if (charset != null) { messageTypeWithCharset = messageType + ";charset=" + charset; } else { messageTypeWithCharset = messageType; } log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]"); if (attachments == null || attachments.size() == 0) { //msg.setContent(message, messageType); msg.setContent(message, messageTypeWithCharset); } else { Multipart multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); //messageBodyPart.setContent(message, messageType); messageBodyPart.setContent(message, messageTypeWithCharset); multipart.addBodyPart(messageBodyPart); iter = attachments.iterator(); while (iter.hasNext()) { Element attachmentElement = (Element) iter.next(); String attachmentText = XmlUtils.getStringValue(attachmentElement); String attachmentName = attachmentElement.getAttribute("name"); String attachmentUrl = attachmentElement.getAttribute("url"); String attachmentType = attachmentElement.getAttribute("type"); String attachmentBase64 = attachmentElement.getAttribute("base64"); if (StringUtils.isEmpty(attachmentType)) { attachmentType = getDefaultAttachmentType(); } if (StringUtils.isEmpty(attachmentName)) { attachmentName = getDefaultAttachmentName(); } log.debug("found attachment [" + attachmentName + "] type [" + attachmentType + "] url [" + attachmentUrl + "]contents [" + attachmentText + "]"); messageBodyPart = new MimeBodyPart(); DataSource attachmentDataSource; if (!StringUtils.isEmpty(attachmentUrl)) { attachmentDataSource = new URLDataSource(new URL(attachmentUrl)); messageBodyPart.setDataHandler(new DataHandler(attachmentDataSource)); } messageBodyPart.setFileName(attachmentName); if ("true".equalsIgnoreCase(attachmentBase64)) { messageBodyPart.setDataHandler(decodeBase64(attachmentText)); } else { messageBodyPart.setText(attachmentText); } multipart.addBodyPart(messageBodyPart); } msg.setContent(multipart); } log.debug(sb.toString()); msg.setSentDate(new Date()); msg.saveChanges(); // send the message putOnTransport(msg); // return the mail in mail-safe from ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); byte[] byteArray = out.toByteArray(); return Misc.byteArrayToString(byteArray, "\n", false); } catch (Exception e) { throw new SenderException("MailSender got error", e); } }
From source file:com.smartitengineering.emailq.service.impl.EmailServiceImpl.java
private void addAttachment(Multipart multipart, Attachments attachment) throws MessagingException { MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setFileName(attachment.getName()); if (StringUtils.isNotBlank(attachment.getDescription())) { attachmentPart.setDescription(attachment.getDescription()); }//www.ja v a 2 s. c om if (StringUtils.isNotBlank(attachment.getDisposition())) { attachmentPart.setDisposition(attachment.getDisposition()); } DataSource source = new ByteArrayDataSource(attachment.getBlob(), attachment.getContentType()); attachmentPart.setDataHandler(new DataHandler(source)); multipart.addBodyPart(attachmentPart); }
From source file:org.pentaho.platform.util.Emailer.java
public boolean send() { String from = props.getProperty("mail.from.default"); String fromName = props.getProperty("mail.from.name"); String to = props.getProperty("to"); String cc = props.getProperty("cc"); String bcc = props.getProperty("bcc"); boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth")); String subject = props.getProperty("subject"); String body = props.getProperty("body"); logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject + "' and the body " + body); try {/*from w ww. j a v a2s . c o m*/ // Get a Session object Session session; if (authenticate) { session = Session.getInstance(props, authenticator); } else { session = Session.getInstance(props); } // if debugging is not set in the email config file, then default to false if (!props.containsKey("mail.debug")) { //$NON-NLS-1$ session.setDebug(false); } final MimeMessage msg; if (EMBEDDED_HTML.equals(attachmentMimeType)) { //Message is ready msg = new MimeMessage(session, attachment); if (body != null) { //We need to add message to the top of the email body final MimeMultipart oldMultipart = (MimeMultipart) msg.getContent(); final MimeMultipart newMultipart = new MimeMultipart("related"); for (int i = 0; i < oldMultipart.getCount(); i++) { BodyPart bodyPart = oldMultipart.getBodyPart(i); final Object content = bodyPart.getContent(); //Main HTML body if (content instanceof String) { final String newContent = body + "<br/><br/>" + content; final MimeBodyPart part = new MimeBodyPart(); part.setText(newContent, "UTF-8", "html"); newMultipart.addBodyPart(part); } else { //CID attachments newMultipart.addBodyPart(bodyPart); } } msg.setContent(newMultipart); } } else { // construct the message msg = new MimeMessage(session); Multipart multipart = new MimeMultipart(); if (attachment == null) { logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$ return false; } ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType); if (body != null) { MimeBodyPart bodyMessagePart = new MimeBodyPart(); bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding()); multipart.addBodyPart(bodyMessagePart); } // attach the file to the message MimeBodyPart attachmentBodyPart = new MimeBodyPart(); attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null)); multipart.addBodyPart(attachmentBodyPart); // add the Multipart to the message msg.setContent(multipart); } if (from != null) { msg.setFrom(new InternetAddress(from, fromName)); } else { // There should be no way to get here logger.error("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()); } msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); return true; } catch (SendFailedException e) { logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$ } catch (AuthenticationFailedException e) { logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$ } catch (Throwable e) { logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$ } return false; }
From source file:bean.RedSocial.java
/** * // w ww . j ava 2 s .c o m * @param _username * @param _email * @param _password */ @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = transactionalBusinessException.ComentariosViaException.class) public void solicitarAcceso(String _username, String _email, String _password) { if (daoUsuario.obtenerUsuario(_username) != null) { throw new exceptionsBusiness.UsernameNoDisponible(); } String hash = BCrypt.hashpw(_password, BCrypt.gensalt()); Token token = new Token(_username, _email, hash); daoToken.guardarToken(token); //enviar token de acceso a la direccion email String correoEnvia = "skala2climbing@gmail.com"; String claveCorreo = "vNspLa5H"; // La configuracin para enviar correo Properties properties = new Properties(); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.auth", "true"); properties.put("mail.user", correoEnvia); properties.put("mail.password", claveCorreo); // Obtener la sesion Session session = Session.getInstance(properties, null); try { // Crear el cuerpo del mensaje MimeMessage mimeMessage = new MimeMessage(session); // Agregar quien enva el correo mimeMessage.setFrom(new InternetAddress(correoEnvia, "Skala2Climbing")); // Los destinatarios InternetAddress[] internetAddresses = { new InternetAddress(token.getEmail()) }; // Agregar los destinatarios al mensaje mimeMessage.setRecipients(Message.RecipientType.TO, internetAddresses); // Agregar el asunto al correo mimeMessage.setSubject("Confirmacin de registro"); // Creo la parte del mensaje MimeBodyPart mimeBodyPart = new MimeBodyPart(); String ip = "90.165.24.228"; mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: http://" + ip + ":8383/redsocialcolaborativaclientangularjs/confirmacion.html?" + "token=" + token.getToken()); //mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: "+"Enlace an no disponible"); // Crear el multipart para agregar la parte del mensaje anterior Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); // Agregar el multipart al cuerpo del mensaje mimeMessage.setContent(multipart); // Enviar el mensaje Transport transport = session.getTransport("smtp"); transport.connect(correoEnvia, claveCorreo); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); transport.close(); } catch (UnsupportedEncodingException | MessagingException ex) { throw new ErrorEnvioEmail(); } }
From source file:com.smartitengineering.emailq.service.impl.EmailServiceImpl.java
protected void sendEmail(Email email, List<Email> successfulEmails) { try {//from ww w . j a v a2 s . c o m if (logger.isDebugEnabled()) { logger.debug("Attempting to send " + email.getId() + " " + email.getSubject()); if (email.getTo() != null) { logger.debug("To: " + Arrays.toString(email.getTo().toArray())); } else { logger.debug("To is NULL"); } if (email.getTo() != null) { logger.debug("CC: " + Arrays.toString(email.getCc().toArray())); } else { logger.debug("CC is NULL"); } if (email.getTo() != null) { logger.debug("BCC: " + Arrays.toString(email.getBcc().toArray())); } else { logger.debug("BCC is NULL"); } if (email.getTo() != null) { logger.debug("FROM: " + email.getFrom()); } else { logger.debug("FROM is NULL"); } if (email.getAttachments() != null) { logger.debug("Attachments: " + Arrays.toString(email.getAttachments().toArray())); for (Attachments attachment : email.getAttachments()) { logger.debug("Attachment: " + attachment.getName()); } } else { logger.debug("No attachments"); } } //Send email if (StringUtils.isBlank(email.getSubject()) || StringUtils.isBlank(email.getFrom())) { logger.warn(new StringBuilder("Invalid email without either from or a subject, thus ignoring it ") .append(email.getId()).toString()); return; } MimeMessage message = new MimeMessage(session); message.setSubject(email.getSubject()); message.setFrom(new InternetAddress(email.getFrom())); addRecipients(message, Message.RecipientType.TO, email.getTo()); addRecipients(message, Message.RecipientType.CC, email.getCc()); addRecipients(message, Message.RecipientType.BCC, email.getBcc()); if (email.getMessage() != null && StringUtils.isNotBlank(email.getMessage().getMsgBody()) && email.getMessage().getMsgType().equals(MsgType.PLAIN) && (email.getAttachments() == null || email.getAttachments().isEmpty())) { message.setText(email.getMessage().getMsgBody()); } else { Multipart multipart = new MimeMultipart(); if (email.getMessage() != null && StringUtils.isNotBlank(email.getMessage().getMsgBody())) { MimeBodyPart bodyPart = new MimeBodyPart(); switch (email.getMessage().getMsgType()) { case HTML: bodyPart.setContent(email.getMessage().getMsgBody(), "html"); break; case PLAIN: default: bodyPart.setText(email.getMessage().getMsgBody()); } multipart.addBodyPart(bodyPart); } if (email.getAttachments() != null && !email.getAttachments().isEmpty()) { for (Attachments attachment : email.getAttachments()) { addAttachment(multipart, attachment); } } message.setContent(multipart); } Transport.send(message); if (logger.isDebugEnabled()) { logger.debug("Sent " + email.getId()); } //Update status email.setMailStatus(Email.MailStatus.SENT); successfulEmails.add(email); if (logger.isDebugEnabled()) { logger.debug("Set new mail status and add to successful queue " + email.getSubject()); } } catch (Exception ex) { logger.warn( new StringBuilder("Error sending email with subject ").append(email.getSubject()).toString(), ex); } }