List of usage examples for javax.mail Multipart addBodyPart
public synchronized void addBodyPart(BodyPart part) throws MessagingException
From source file:org.data2semantics.yasgui.selenium.FailNotification.java
private void sendMail(String subject, String content, String fileName) { Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(baseTest.props.getMailUserName(), baseTest.props.getMailPassWord()); }/*w ww. j a v a 2 s. c om*/ }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(baseTest.props.getMailUserName())); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(baseTest.props.getMailSendTo())); message.setSubject(subject); message.setContent(content, "text/html; charset=utf-8"); MimeBodyPart messageBodyPart = new MimeBodyPart(); // message body messageBodyPart.setContent(content, "text/html; charset=utf-8"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // attachment messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(fileName); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName("screenshot.png"); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); Transport.send(message); System.out.println("Email send"); } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:com.autentia.tnt.mail.DefaultMailService.java
public void sendOutputStreams(String to, String subject, String text, Map<InputStream, String> attachments) throws MessagingException { Transport t = null;//from w w w.j a v a 2s.c om try { MimeMessage message = new MimeMessage(session); t = session.getTransport("smtp"); message.setFrom(new InternetAddress(configurationUtil.getMailUsername())); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setSentDate(new Date()); if (attachments == null || attachments.size() < 1) { message.setText(text); } else { // create the message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(text); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); try { for (InputStream attachment : attachments.keySet()) { messageBodyPart = new MimeBodyPart(); DataSource source = new ByteArrayDataSource(attachment, "application/octet-stream"); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachments.get(attachment)); //NOSONAR multipart.addBodyPart(messageBodyPart); //Se emplea keyset y no valueset porque se emplea tanto la key como el val } } catch (IOException e) { throw new MessagingException("cannot add an attachment to mail", e); } message.setContent(multipart); } t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword()); t.sendMessage(message, message.getAllRecipients()); } finally { if (t != null) { t.close(); } } }
From source file:com.intuit.tank.mail.TankMailer.java
/** * @{inheritDoc// w w w . java2 s . c om */ @Override public void sendMail(MailMessage message, String... emailAddresses) { MailConfig mailConfig = new TankConfig().getMailConfig(); Properties props = new Properties(); props.put("mail.smtp.host", mailConfig.getSmtpHost()); props.put("mail.smtp.port", mailConfig.getSmtpPort()); Session mailSession = Session.getDefaultInstance(props); Message simpleMessage = new MimeMessage(mailSession); InternetAddress fromAddress = null; InternetAddress toAddress = null; try { fromAddress = new InternetAddress(mailConfig.getMailFrom()); simpleMessage.setFrom(fromAddress); for (String email : emailAddresses) { try { toAddress = new InternetAddress(email); simpleMessage.addRecipient(RecipientType.TO, toAddress); } catch (AddressException e) { LOG.warn("Error with recipient " + email + ": " + e.toString()); } } simpleMessage.setSubject(message.getSubject()); final MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent(message.getPlainTextBody(), "text/plain"); textPart.setHeader("MIME-Version", "1.0"); textPart.setHeader("Content-Type", textPart.getContentType()); // HTML version final MimeBodyPart htmlPart = new MimeBodyPart(); // htmlPart.setContent(message.getHtmlBody(), "text/html"); htmlPart.setDataHandler(new DataHandler(new HTMLDataSource(message.getHtmlBody()))); htmlPart.setHeader("MIME-Version", "1.0"); htmlPart.setHeader("Content-Type", "text/html"); // Create the Multipart. Add BodyParts to it. final Multipart mp = new MimeMultipart("alternative"); mp.addBodyPart(textPart); mp.addBodyPart(htmlPart); // Set Multipart as the message's content simpleMessage.setContent(mp); simpleMessage.setHeader("MIME-Version", "1.0"); simpleMessage.setHeader("Content-Type", mp.getContentType()); logMsg(mailConfig.getSmtpHost(), simpleMessage); if (simpleMessage.getRecipients(RecipientType.TO) != null && simpleMessage.getRecipients(RecipientType.TO).length > 0) { Transport.send(simpleMessage); } } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:de.elomagic.mag.AbstractTest.java
protected MimeMessage createMimeMessage(String filename) throws Exception { MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent("This is some text to be displayed inline", "text/plain"); textPart.setDisposition(Part.INLINE); MimeBodyPart binaryPart = new MimeBodyPart(); InputStream in = getClass().getResourceAsStream("/TestFile.pdf"); binaryPart.setContent(getOriginalMailAttachment(), "application/pdf"); binaryPart.setDisposition(Part.ATTACHMENT); binaryPart.setFileName(filename);/*from ww w. j a v a 2 s .c o m*/ Multipart mp = new MimeMultipart(); mp.addBodyPart(textPart); mp.addBodyPart(binaryPart); MimeMessage message = new MimeMessage(greenMail.getImap().createSession()); message.setRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress("mailuser@localhost.com") }); message.setSubject("Another test mail subject"); message.setContent(mp); // return message; // GreenMailUtil.createTextEmail("to@localhost.com", "from@localhost.com", "subject", "body", greenMail.getImap().getServerSetup()); }
From source file:be.fedict.eid.dss.model.bean.TaskMDB.java
private void sendMail(String mailTo, String subject, String messageBody, String attachmentMimetype, byte[] attachment) { LOG.debug("sending email to " + mailTo + " with subject \"" + subject + "\""); String smtpServer = this.configuration.getValue(ConfigProperty.SMTP_SERVER, String.class); if (null == smtpServer || smtpServer.trim().isEmpty()) { LOG.warn("no SMTP server configured"); return;// w w w .j a v a 2s. c o m } String mailFrom = this.configuration.getValue(ConfigProperty.MAIL_FROM, String.class); if (null == mailFrom || mailFrom.trim().isEmpty()) { LOG.warn("no mail from address configured"); return; } LOG.debug("mail from: " + mailFrom); Properties props = new Properties(); props.put("mail.smtp.host", smtpServer); props.put("mail.from", mailFrom); String mailPrefix = this.configuration.getValue(ConfigProperty.MAIL_PREFIX, String.class); if (null != mailPrefix && false == mailPrefix.trim().isEmpty()) { subject = "[" + mailPrefix.trim() + "] " + subject; } Session session = Session.getInstance(props, null); try { MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(); mimeMessage.setRecipients(RecipientType.TO, mailTo); mimeMessage.setSubject(subject); mimeMessage.setSentDate(new Date()); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setText(messageBody); Multipart multipart = new MimeMultipart(); // first part is body multipart.addBodyPart(mimeBodyPart); // second part is attachment if (null != attachment) { MimeBodyPart attachmentMimeBodyPart = new MimeBodyPart(); DataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimetype); attachmentMimeBodyPart.setDataHandler(new DataHandler(dataSource)); multipart.addBodyPart(attachmentMimeBodyPart); } mimeMessage.setContent(multipart); Transport.send(mimeMessage); } catch (MessagingException e) { throw new RuntimeException("send failed, exception: " + e.getMessage(), e); } }
From source file:org.grouter.common.mail.MailHandler.java
/** * Creates a multipart email with html and plain text email body to fallback to if * email client do not handle html base emails. * * @param mimeMessage// w ww.j a v a2 s. co m * @param dto * @throws MessagingException */ private void createHtmlAndPlainTextBody(MimeMessage mimeMessage, MailDto dto) throws MessagingException { if (StringUtils.isNotEmpty(dto.getHtmlTextBody())) { mimeMessage.setContentID(MailDto.CONTENT_TYPE_MULTIPART_ALTERNATIVE); // Create your text message part BodyPart plainBodyPart = new MimeBodyPart(); plainBodyPart.setContent(dto.getPlainTextBody(), MailDto.CONTENT_TYPE_TEXT_PLAIN); // Create a multi-part to combine the parts Multipart multipart = new MimeMultipart("alternative"); multipart.addBodyPart(plainBodyPart); StringBuilder sb = new StringBuilder(); sb.append(PRE_HTML_HEADER); sb.append(dto.getSubject()).append("\n"); sb.append(POST_HTML_HEADER); sb.append(dto.getHtmlTextBody()); sb.append(END_HTML); BodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(sb.toString(), MailDto.CONTENT_TYPE_TEXT_HTML); // Add html part to multi part multipart.addBodyPart(htmlBodyPart); mimeMessage.setContent(multipart); } else { mimeMessage.setSubject(dto.getSubject()); mimeMessage.setText(dto.getPlainTextBody()); mimeMessage.setContent(dto.getPlainTextBody(), MailDto.CONTENT_TYPE_TEXT_PLAIN); } }
From source file:org.codice.alliance.core.email.impl.EmailSenderImpl.java
/** sendEmail method sends email after receiving input parameters */ @Override//from w w w .ja v a 2 s. c o m public void sendEmail(String fromEmail, String toEmail, String subject, String body, List<Pair<String, InputStream>> attachments) throws IOException { notNull(fromEmail, "fromEmail must be non-null"); notNull(toEmail, "toEmail must be non-null"); notNull(subject, "subject must be non-null"); notNull(body, "body must be non-null"); notNull(attachments, "attachments must be non-null"); if (StringUtils.isBlank(mailHost)) { throw new IOException("the mail server hostname has not been configured"); } List<File> tempFiles = new LinkedList<>(); try { InternetAddress emailAddr = new InternetAddress(toEmail); emailAddr.validate(); Properties properties = createSessionProperties(); Session session = Session.getDefaultInstance(properties); MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(new InternetAddress(fromEmail)); mimeMessage.addRecipient(Message.RecipientType.TO, emailAddr); mimeMessage.setSubject(subject); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); Holder<Long> bytesWritten = new Holder<>(0L); for (Pair<String, InputStream> attachment : attachments) { messageBodyPart = new MimeBodyPart(); File file = File.createTempFile("email-sender-", ".dat"); tempFiles.add(file); copyDataToTempFile(file, attachment.getValue(), bytesWritten); messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(file))); messageBodyPart.setFileName(attachment.getKey()); multipart.addBodyPart(messageBodyPart); } mimeMessage.setContent(multipart); send(mimeMessage); LOGGER.debug("Email sent to " + toEmail); } catch (AddressException e) { throw new IOException("invalid email address: email=" + toEmail, e); } catch (MessagingException e) { throw new IOException("message error occurred on send", e); } finally { tempFiles.forEach(file -> { if (!file.delete()) { LOGGER.debug("unable to delete tmp file: path={}", file); } }); } }
From source file:mitm.application.djigzo.james.mailets.Attach.java
@Override public void serviceMail(Mail mail) { try {// w w w . j av a2 s. co m MimeMessage sourceMessage = mail.getMessage(); MimeMessage newMessage = retainMessageID ? new MimeMessageWithID(MailSession.getDefaultSession(), sourceMessage.getMessageID()) : new MimeMessage(MailSession.getDefaultSession()); if (StringUtils.isNotEmpty(filename)) { newMessage.setFileName(filename); } Multipart mp = new MimeMultipart(); HeaderMatcher contentMatcher = new ContentHeaderNameMatcher(); mp.addBodyPart(BodyPartUtils.makeContentBodyPart(sourceMessage, contentMatcher)); newMessage.setContent(mp); /* * create a matcher that matches on everything expect content-* */ HeaderMatcher nonContentMatcher = new NotHeaderNameMatcher(contentMatcher); /* * copy all non-content headers from source message to the new message */ HeaderUtils.copyHeaders(sourceMessage, newMessage, nonContentMatcher); newMessage.saveChanges(); mail.setMessage(newMessage); } catch (MessagingException e) { getLogger().error("Error attaching the message.", e); } catch (IOException e) { getLogger().error("Error attaching the message.", e); } }
From source file:egovframework.oe1.cms.cmm.notify.email.service.impl.EgovOe1SSLMailServiceImpl.java
protected void send(String subject, String content, String contentType) throws Exception { Properties props = new Properties(); props.put("mail.transport.protocol", "smtps"); props.put("mail.smtps.host", getHost()); props.put("mail.smtps.auth", "true"); Session mailSession = Session.getDefaultInstance(props); mailSession.setDebug(false);/*from w w w. j ava 2 s. c o m*/ Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress("www.egovframe.org", "webmaster", "euc-kr")); message.setSubject(subject); MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(content, "utf-8"); Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); List<String> fileNames = getAtchFileIds(); for (Iterator<String> it = fileNames.iterator(); it.hasNext();) { MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(it.next()); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr", "B")); // Q : ascii, B : mp.addBodyPart(mbp2); } // add the Multipart to the message message.setContent(mp); for (Iterator<String> it = getReceivers().iterator(); it.hasNext();) message.addRecipient(Message.RecipientType.TO, new InternetAddress(it.next())); transport.connect(getHost(), getPort(), getUsername(), getPassword()); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); transport.close(); }
From source file:org.alfresco.tutorial.repoaction.SendAsEmailActionExecuter.java
@Override protected void executeImpl(Action action, NodeRef actionedUponNodeRef) { if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == true) { // Get the email properties entered via Share Form String to = (String) action.getParameterValue(PARAM_EMAIL_TO_NAME); String subject = (String) action.getParameterValue(PARAM_EMAIL_SUBJECT_NAME); String body = (String) action.getParameterValue(PARAM_EMAIL_BODY_NAME); // Get document filename Serializable filename = serviceRegistry.getNodeService().getProperty(actionedUponNodeRef, ContentModel.PROP_NAME); if (filename == null) { throw new AlfrescoRuntimeException("Document filename is null"); }//from w w w . j av a 2s.co m String documentName = (String) filename; try { // Create mail session Properties mailServerProperties = new Properties(); mailServerProperties = System.getProperties(); mailServerProperties.put("mail.smtp.host", "localhost"); mailServerProperties.put("mail.smtp.port", "2525"); Session session = Session.getDefaultInstance(mailServerProperties, null); session.setDebug(false); // Define message Message message = new MimeMessage(session); String fromAddress = "training@alfresco.com"; message.setFrom(new InternetAddress(fromAddress)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); // Create the message part with body text BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Create the Attachment part // // Get the document content bytes byte[] documentData = getDocumentContentBytes(actionedUponNodeRef, documentName); if (documentData == null) { throw new AlfrescoRuntimeException("Document content is null"); } // Attach document messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(documentData, new MimetypesFileTypeMap().getContentType(documentName)))); messageBodyPart.setFileName(documentName); multipart.addBodyPart(messageBodyPart); // Put parts in message message.setContent(multipart); // Send mail Transport.send(message); // Set status on node as "sent via email" Map<QName, Serializable> properties = new HashMap<QName, Serializable>(); properties.put(ContentModel.PROP_ORIGINATOR, fromAddress); properties.put(ContentModel.PROP_ADDRESSEE, to); properties.put(ContentModel.PROP_SUBJECT, subject); properties.put(ContentModel.PROP_SENTDATE, new Date()); serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, ContentModel.ASPECT_EMAILED, properties); } catch (MessagingException me) { me.printStackTrace(); throw new AlfrescoRuntimeException("Could not send email: " + me.getMessage()); } } }