List of usage examples for javax.mail.internet MimeMultipart MimeMultipart
public MimeMultipart()
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()); }/*from 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.silverpeas.mailinglist.service.job.TestMessageCheckerWithStubs.java
@Test public void testCheckNewMessages() throws MessagingException, IOException { org.jvnet.mock_javamail.Mailbox.clearAll(); MessageChecker messageChecker = getMessageChecker(); messageChecker.removeListener("componentId"); messageChecker.removeListener("thesimpsons@silverpeas.com"); messageChecker.removeListener("theflanders@silverpeas.com"); StubMessageListener mockListener1 = new StubMessageListener("thesimpsons@silverpeas.com"); StubMessageListener mockListener2 = new StubMessageListener("theflanders@silverpeas.com"); messageChecker.addMessageListener(mockListener1); messageChecker.addMessageListener(mockListener2); MimeMessage mail = new MimeMessage(messageChecker.getMailSession()); InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com"); InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Plain text Email test with attachment"); MimeBodyPart attachment = new MimeBodyPart( TestMessageCheckerWithStubs.class.getResourceAsStream("lemonde.html")); attachment.setDisposition(Part.INLINE); attachment.setFileName("lemonde.html"); MimeBodyPart body = new MimeBodyPart(); body.setText(textEmailContent);/*from w w w . j av a 2 s .c o m*/ Multipart multiPart = new MimeMultipart(); multiPart.addBodyPart(body); multiPart.addBodyPart(attachment); mail.setContent(multiPart); mail.setSentDate(new Date()); Date sentDate1 = new Date(mail.getSentDate().getTime()); Transport.send(mail); mail = new MimeMessage(messageChecker.getMailSession()); bart = new InternetAddress("bart.simpson@silverpeas.com"); theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Plain text Email test"); mail.setText(textEmailContent); mail.setSentDate(new Date()); Date sentDate2 = new Date(mail.getSentDate().getTime()); Transport.send(mail); //Unauthorized email mail = new MimeMessage(messageChecker.getMailSession()); bart = new InternetAddress("marge.simpson@silverpeas.com"); theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Plain text Email test"); mail.setText(textEmailContent); mail.setSentDate(new Date()); Transport.send(mail); assertThat(org.jvnet.mock_javamail.Mailbox.get("thesimpsons@silverpeas.com").size(), is(3)); messageChecker.checkNewMessages(new Date()); assertThat(mockListener2.getMessageEvent(), is(nullValue())); MessageEvent event = mockListener1.getMessageEvent(); assertThat(event, is(notNullValue())); assertThat(event.getMessages(), is(notNullValue())); assertThat(event.getMessages(), hasSize(2)); Message message = event.getMessages().get(0); assertThat(message.getSender(), is("bart.simpson@silverpeas.com")); assertThat(message.getTitle(), is("Plain text Email test with attachment")); assertThat(message.getBody(), is(textEmailContent)); assertThat(message.getSummary(), is(textEmailContent.substring(0, 200))); assertThat(message.getSentDate().getTime(), is(sentDate1.getTime())); assertThat(message.getAttachmentsSize(), greaterThan(0L)); assertThat(message.getAttachments(), hasSize(1)); String path = MessageFormat.format(theSimpsonsAttachmentPath, new Object[] { messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId()) }); Attachment attached = message.getAttachments().iterator().next(); assertThat(attached.getPath(), is(path)); assertThat(message.getComponentId(), is("thesimpsons@silverpeas.com")); message = event.getMessages().get(1); assertThat(message.getSender(), is("bart.simpson@silverpeas.com")); assertThat(message.getTitle(), is("Plain text Email test")); assertThat(message.getBody(), is(textEmailContent)); assertThat(message.getSummary(), is(textEmailContent.substring(0, 200))); assertThat(message.getAttachmentsSize(), is(0L)); assertThat(message.getAttachments(), hasSize(0)); assertThat(message.getComponentId(), is("thesimpsons@silverpeas.com")); assertThat(message.getSentDate().getTime(), is(sentDate2.getTime())); }
From source file:AmazonSESSample.java
private static RawMessage getRawMessage() throws MessagingException, IOException { // JavaMail representation of the message Session s = Session.getInstance(new Properties(), null); s.setDebug(true);/* www.j a v a2 s . c om*/ MimeMessage msg = new MimeMessage(s); // Sender and recipient msg.setFrom(new InternetAddress("aravind@gofastpay.com")); InternetAddress[] address = { new InternetAddress("aravind@gofastpay.com") }; msg.setRecipients(javax.mail.Message.RecipientType.TO, address); msg.setSentDate(new Date()); // Subject msg.setSubject(SUBJECT); // Add a MIME part to the message //MimeMultipart mp = new MimeMultipart(); Multipart mp = new MimeMultipart(); MimeBodyPart mimeBodyPart = new MimeBodyPart(); //mimeBodyPart.setText(BODY); //BodyPart part = new MimeBodyPart(); //String myText = BODY; //part.setContent(URLEncoder.encode(myText, "US-ASCII"), "text/html"); //part.setText(BODY); //mp.addBodyPart(part); //msg.setContent(mp); mimeBodyPart.setContent(BODY, "text/html"); mp.addBodyPart(mimeBodyPart); msg.setContent(mp); // Print the raw email content on the console //PrintStream out = System.out; ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); //String rawString = out.toString(); //byte[] bytes = IOUtils.toByteArray(msg.getInputStream()); //ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length); //ByteBuffer byteBuffer = ByteBuffer.wrap(Base64.getEncoder().encode(rawString.getBytes())); //byteBuffer.put(bytes); //byteBuffer.put(Base64.getEncoder().encode(bytes)); RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(out.toByteArray())); return rawMessage; }
From source file:com.threepillar.labs.meeting.email.EmailInviteImpl.java
@Override public void sendInvite(final String subject, final String description, final Participant from, final List<Participant> attendees, final Date startDate, final Date endDate, final String location) throws Exception { this.properties.put("mail.smtp.socketFactory.port", properties.get("mail.smtp.port")); this.properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); this.properties.put("mail.smtp.socketFactory.fallback", "false"); validate();/*from ww w .j a v a2s .c o m*/ LOG.info("Sending meeting invite"); LOG.debug("Mail Properties :: " + this.properties); Session session; if (password != null) { session = Session.getInstance(this.properties, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } else { session = Session.getInstance(this.properties); } ICal cal = new ICal(subject, description, from, attendees, startDate, endDate, location); cal.init(); StringBuffer sb = new StringBuffer(); sb.append(from.getEmail()); for (Participant bean : attendees) { if (sb.length() > 0) { sb.append(","); } sb.append(bean.getEmail()); } MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from.getEmail())); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sb.toString())); message.setSubject(subject); Multipart multipart = new MimeMultipart(); MimeBodyPart iCal = new MimeBodyPart(); iCal.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(cal.toByteArray()), "text/calendar;method=REQUEST;charset=\"UTF-8\""))); LOG.debug("Calender Request :: \n" + cal.toString()); multipart.addBodyPart(iCal); message.setContent(multipart); Transport.send(message); }
From source file:bioLockJ.module.agent.MailAgent.java
private Multipart getContent() throws Exception { final Multipart multipart = new MimeMultipart(); final BodyPart messageBodyPart = new MimeBodyPart(); final List<BodyPart> attachments = getAttachments(); messageBodyPart.setText(getSummary()); multipart.addBodyPart(messageBodyPart); for (final BodyPart bp : attachments) { multipart.addBodyPart(bp);/* w w w . jav a 2s . com*/ } return multipart; }
From source file:net.duckling.ddl.service.mail.impl.MailServiceImpl.java
public void sendMail(Mail mail) { LOG.debug("sendEmail() to: " + mail.getRecipient()); try {/* ww w. ja v a 2 s. c o m*/ Session session = Session.getInstance(m_bag.m_mailProperties, m_bag.m_authenticator); session.setDebug(false); MimeMessage msg = new MimeMessage(session); msg.setFrom(m_bag.m_fromAddress); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getRecipient())); msg.setSubject(mail.getSubject()); msg.setSentDate(new Date()); Multipart mp = new MimeMultipart(); MimeBodyPart txtmbp = new MimeBodyPart(); txtmbp.setContent(mail.getMessage(), EMAIL_CONTENT_TYPE); mp.addBodyPart(txtmbp); List<String> attachments = mail.getAttachments(); for (Iterator<String> it = attachments.iterator(); it.hasNext();) { MimeBodyPart mbp = new MimeBodyPart(); String filename = it.next(); FileDataSource fds = new FileDataSource(filename); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(MimeUtility.encodeText(fds.getName())); mp.addBodyPart(mbp); } msg.setContent(mp); if ((m_bag.m_fromAddress != null) && (m_bag.m_fromAddress.getAddress() != null) && (m_bag.m_fromAddress.getAddress().indexOf("@") != -1)) { cheat(msg, m_bag.m_fromAddress.getAddress().substring(m_bag.m_fromAddress.getAddress().indexOf("@"))); } Transport.send(msg); LOG.info("Successfully send the mail to " + mail.getRecipient()); } catch (Throwable e) { LOG.error("Exception occured while trying to send notification to: " + mail.getRecipient(), e); LOG.debug("Details:", e); } }
From source file:org.eclipse.ecr.automation.core.mail.Composer.java
public Mailer.Message newMixedMessage(String templateContent, Object ctx, String textType, List<Blob> attachments) throws Exception { if (textType == null) { textType = "plain"; }/*w w w .j a va 2s . c o m*/ Mailer.Message msg = mailer.newMessage(); MimeMultipart mp = new MimeMultipart(); MimeBodyPart body = new MimeBodyPart(); String result = render(templateContent, ctx); body.setText(result, "UTF-8", textType); mp.addBodyPart(body); for (Blob blob : attachments) { MimeBodyPart a = new MimeBodyPart(); a.setDataHandler(new DataHandler(new BlobDataSource(blob))); a.setFileName(blob.getFilename()); mp.addBodyPart(a); } msg.setContent(mp); return msg; }
From source file:eagle.common.email.EagleMailClient.java
private boolean _send(String from, String to, String cc, String title, String content, List<MimeBodyPart> attachments) { MimeMessage mail = new MimeMessage(session); try {/*from w w w. ja va 2s . c o m*/ mail.setFrom(new InternetAddress(from)); mail.setSubject(title); if (to != null) { mail.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); } if (cc != null) { mail.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc)); } //mail.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(DEFAULT_BCC_ADDRESS)); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(content, "text/html;charset=utf-8"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); for (MimeBodyPart attachment : attachments) { multipart.addBodyPart(attachment); } mail.setContent(multipart); // mail.setContent(content, "text/html;charset=utf-8"); LOG.info(String.format("Going to send mail: from[%s], to[%s], cc[%s], title[%s]", from, to, cc, title)); Transport.send(mail); return true; } catch (AddressException e) { LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e); return false; } catch (MessagingException e) { LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e); return false; } }
From source file:com.github.thorqin.toolkit.mail.MailService.java
private void sendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); final Session session; props.put("mail.smtp.auth", String.valueOf(setting.auth)); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", setting.host); props.put("mail.smtp.port", setting.port); if (setting.secure.equals(SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); } else if (setting.secure.equals(SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", setting.port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); }/* w ww. ja v a 2s . co m*/ if (!setting.auth) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(setting.user, setting.password); } }); if (setting.debug) session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (setting.from != null) message.setFrom(new InternetAddress(setting.from)); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (setting.trace && tracer != null) { Tracer.Info info = new Tracer.Info(); info.catalog = "mail"; info.name = "send"; info.put("sender", StringUtils.join(message.getFrom())); info.put("recipients", mail.to); info.put("SMTPServer", setting.host); info.put("SMTPAccount", setting.user); info.put("subject", mail.subject); info.put("startTime", beginTime); info.put("runningTime", System.currentTimeMillis() - beginTime); tracer.trace(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:org.sakaiproject.kernel.messaging.email.EmailMessageListener.java
public void handleMessage(Message email) throws AddressException, UnsupportedEncodingException, SendFailedException, MessagingException, IOException { String fromAddress = email.getHeader(Message.Field.FROM); if (fromAddress == null) { throw new MessagingException("Unable to send without a 'from' address."); }// www . jav a2 s.c o m // transform to a MimeMessage ArrayList<String> invalids = new ArrayList<String>(); // convert and validate the 'from' address InternetAddress from = new InternetAddress(fromAddress, true); // convert and validate reply to addresses String replyTos = email.getHeader(EmailMessage.Field.REPLY_TO); InternetAddress[] replyTo = emails2Internets(replyTos, invalids); // convert and validate the 'to' addresses String tos = email.getHeader(Message.Field.TO); InternetAddress[] to = emails2Internets(tos, invalids); // convert and validate 'cc' addresses String ccs = email.getHeader(EmailMessage.Field.CC); InternetAddress[] cc = emails2Internets(ccs, invalids); // convert and validate 'bcc' addresses String bccs = email.getHeader(EmailMessage.Field.BCC); InternetAddress[] bcc = emails2Internets(bccs, invalids); int totalRcpts = to.length + cc.length + bcc.length; if (totalRcpts == 0) { throw new MessagingException("No recipients to send to."); } MimeMessage mimeMsg = new MimeMessage(session); mimeMsg.setFrom(from); mimeMsg.setReplyTo(replyTo); mimeMsg.setRecipients(RecipientType.TO, to); mimeMsg.setRecipients(RecipientType.CC, cc); mimeMsg.setRecipients(RecipientType.BCC, bcc); // add in any additional headers Map<String, String> headers = email.getHeaders(); if (headers != null && !headers.isEmpty()) { for (Entry<String, String> header : headers.entrySet()) { mimeMsg.setHeader(header.getKey(), header.getValue()); } } // add the content to the message List<Message> parts = email.getParts(); if (parts == null || parts.size() == 0) { setContent(mimeMsg, email); } else { // create a multipart container Multipart multipart = new MimeMultipart(); // create a body part for the message text MimeBodyPart msgBodyPart = new MimeBodyPart(); setContent(msgBodyPart, email); // add the message part to the container multipart.addBodyPart(msgBodyPart); // add attachments for (Message part : parts) { addPart(multipart, part); } // set the multipart container as the content of the message mimeMsg.setContent(multipart); } if (allowTransport) { // send Transport.send(mimeMsg); } else { try { ByteArrayOutputStream output = new ByteArrayOutputStream(); mimeMsg.writeTo(output); String emailString = output.toString(); LOG.info(emailString); observable.notifyObservers(emailString); } catch (IOException e) { LOG.info("Transport disabled and unable to write message to log: " + e.getMessage(), e); } } }