List of usage examples for javax.mail.internet MimeMessage MimeMessage
public MimeMessage(MimeMessage source) throws MessagingException
source
MimeMessage. From source file:com.silverpeas.mailinglist.service.notification.TestNotificationHelper.java
@Test public void testSimpleSendMail() throws Exception { MimeMessage mail = new MimeMessage(notificationHelper.getSession()); InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { theSimpsons }); mail.setSubject("Simple text Email test"); mail.setText(textEmailContent);//from ww w. j a va2s . co m List<ExternalUser> externalUsers = new LinkedList<ExternalUser>(); ExternalUser user = new ExternalUser(); user.setComponentId("100"); user.setEmail("bart.simpson@silverpeas.com"); externalUsers.add(user); notificationHelper.sendMail(mail, externalUsers); checkSimpleEmail("bart.simpson@silverpeas.com", "Simple text Email test"); }
From source file:org.ktunaxa.referral.server.command.email.SendEmailCommand.java
public void execute(final SendEmailRequest request, final SendEmailResponse response) throws Exception { final String from = request.getFrom(); if (null == from) { throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "from"); }/*from w ww .j ava2 s . c o m*/ final String to = request.getTo(); if (null == to) { throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "to"); } response.setSuccess(false); final List<HttpGet> attachmentConnections = new ArrayList<HttpGet>(); MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { log.debug("Build mime message"); addRecipients(mimeMessage, Message.RecipientType.TO, to); addRecipients(mimeMessage, Message.RecipientType.CC, request.getCc()); addRecipients(mimeMessage, Message.RecipientType.BCC, request.getBcc()); addReplyTo(mimeMessage, request.getReplyTo()); mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setSubject(request.getSubject()); // mimeMessage.setText(request.getText()); List<String> attachments = request.getAttachmentUrls(); MimeMultipart mp = new MimeMultipart(); MimeBodyPart mailBody = new MimeBodyPart(); mailBody.setText(request.getText()); mp.addBodyPart(mailBody); if (null != attachments && !attachments.isEmpty()) { for (String url : attachments) { log.debug("add mime part for {}", url); MimeBodyPart part = new MimeBodyPart(); String filename = url; int pos = filename.lastIndexOf('/'); if (pos >= 0) { filename = filename.substring(pos + 1); } pos = filename.indexOf('?'); if (pos >= 0) { filename = filename.substring(0, pos); } part.setFileName(filename); String fixedUrl = url; if (fixedUrl.startsWith("../")) { fixedUrl = "http://localhost:8080/" + fixedUrl.substring(3); } fixedUrl = fixedUrl.replace(" ", "%20"); part.setDataHandler(new DataHandler(new URL(fixedUrl))); mp.addBodyPart(part); } } mimeMessage.setContent(mp); log.debug("message {}", mimeMessage); } }; try { if (request.isSendMail()) { mailSender.send(preparator); cleanAttachmentConnection(attachmentConnections); log.debug("mail sent"); } if (request.isSaveMail()) { MimeMessage mimeMessage = new MimeMessage((Session) null); preparator.prepare(mimeMessage); // overwrite multipart body as we don't need the attachments mimeMessage.setText(request.getText()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mimeMessage.writeTo(baos); // add document in referral Crs crs = geoService.getCrs2(KtunaxaConstant.LAYER_CRS); List<InternalFeature> features = vectorLayerService.getFeatures( KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs, filterService.parseFilter(ReferralUtil.createFilter(request.getReferralId())), null, VectorLayerService.FEATURE_INCLUDE_ATTRIBUTES); InternalFeature orgReferral = features.get(0); log.debug("Got referral {}", request.getReferralId()); InternalFeature referral = orgReferral.clone(); List<InternalFeature> newFeatures = new ArrayList<InternalFeature>(); newFeatures.add(referral); Map<String, Attribute> attributes = referral.getAttributes(); OneToManyAttribute orgComments = (OneToManyAttribute) attributes .get(KtunaxaConstant.ATTRIBUTE_COMMENTS); List<AssociationValue> comments = new ArrayList<AssociationValue>(orgComments.getValue()); AssociationValue emailAsComment = new AssociationValue(); emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_TITLE, "Mail: " + request.getSubject()); emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT, new String(baos.toByteArray())); emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATED_BY, securitycontext.getUserName()); emailAsComment.setDateAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATION_DATE, new Date()); emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT, new String(baos.toByteArray())); emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT, new String(baos.toByteArray())); emailAsComment.setBooleanAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_INCLUDE_IN_REPORT, false); comments.add(emailAsComment); OneToManyAttribute newComments = new OneToManyAttribute(comments); attributes.put(KtunaxaConstant.ATTRIBUTE_COMMENTS, newComments); log.debug("Going to add mail as comment to referral"); vectorLayerService.saveOrUpdate(KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs, features, newFeatures); } response.setSuccess(true); } catch (MailException me) { log.error("Could not send e-mail", me); throw new KtunaxaException(KtunaxaException.CODE_MAIL_ERROR, "Could not send e-mail"); } }
From source file:davmail.smtp.TestSmtp.java
public void testInvalidFrom() throws IOException, MessagingException, InterruptedException { String body = "Test message"; MimeMessage mimeMessage = new MimeMessage((Session) null); mimeMessage.addHeader("From", "guessant@loca.net"); mimeMessage.addHeader("To", Settings.getProperty("davmail.to")); mimeMessage.setSubject("Test subject"); mimeMessage.setText(body);/* www . jav a 2 s . com*/ sendAndCheckMessage(mimeMessage, "guessant@loca.net", null); }
From source file:ftpclient.FTPManager.java
public boolean sendUserMail(String uploadedFileName) { if (settings != null) { try {// ww w .j a va 2 s . c om String userEmail = db.getUserEmail(uid); Properties props = System.getProperties(); props.setProperty("mail.smtp.host", settings.getSenderEmailHost()); props.setProperty("mail.smtp.auth", "true"); // props.put("mail.smtp.starttls.enable", "true"); // props.put("mail.smtp.port", "587"); Session s = Session.getDefaultInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(settings.getSenderLogin(), new String(settings.getSenderPassword())); } }); MimeMessage msg = new MimeMessage(s); msg.setFrom(settings.getSenderEmail()); msg.addRecipients(Message.RecipientType.TO, userEmail); msg.setSubject("FTP action"); msg.setText("You have succesfully uploaded file " + uploadedFileName); Transport.send(msg); return true; } catch (MessagingException ex) { Logger.getLogger(FTPManager.class.getName()).log(Level.SEVERE, null, ex); return false; } } else { return false; } }
From source file:it.infn.ct.security.utilities.LDAPCleaner.java
private void sendUserRemainder(UserRequest ur, int days) { javax.mail.Session session = null;/*w w w . jav a2s .c o m*/ try { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); session = (javax.mail.Session) envCtx.lookup("mail/Users"); Message mailMsg = new MimeMessage(session); mailMsg.setFrom(new InternetAddress(rb.getString("mailSender"), rb.getString("IdPAdmin"))); InternetAddress mailTo[] = new InternetAddress[1]; mailTo[0] = new InternetAddress(getGoodMail(ur), ur.getTitle() + " " + ur.getGivenname() + " " + ur.getSurname()); mailMsg.setRecipients(Message.RecipientType.TO, mailTo); if (rb.containsKey("mailCopy") && !rb.getString("mailCopy").isEmpty()) { String ccMail[] = rb.getString("mailCopy").split(";"); InternetAddress mailCCopy[] = new InternetAddress[ccMail.length]; for (int i = 0; i < ccMail.length; i++) { mailCCopy[i] = new InternetAddress(ccMail[i]); } mailMsg.setRecipients(Message.RecipientType.CC, mailCCopy); } if (days > 0) { mailMsg.setSubject( rb.getString("mailNotificationSubject").replace("_DAYS_", Integer.toString(days))); mailMsg.setText(rb.getString("mailNotificationBody") .replaceAll("_USER_", ur.getTitle() + " " + ur.getGivenname() + " " + ur.getSurname()) .replace("_DAYS_", Integer.toString(days))); } else { mailMsg.setSubject(rb.getString("mailDeleteSubject").replace("_DAYS_", Integer.toString(days))); mailMsg.setText(rb.getString("mailDeleteBody") .replaceAll("_USER_", ur.getTitle() + " " + ur.getGivenname() + " " + ur.getSurname()) .replace("_DAYS_", Integer.toString(days))); } Transport.send(mailMsg); } catch (Exception ex) { _log.error("Mail resource lookup error"); _log.error(ex.getMessage()); } }
From source file:cherry.foundation.mail.MailSendHandlerImplTest.java
@Test public void testSendNowAttached() throws Exception { LocalDateTime now = LocalDateTime.now(); MailSendHandler handler = create(now); ArgumentCaptor<MimeMessagePreparator> preparator = ArgumentCaptor.forClass(MimeMessagePreparator.class); doNothing().when(mailSender).send(preparator.capture()); final File file = File.createTempFile("test_", ".txt", new File(".")); file.deleteOnExit();/* w ww . j a va 2 s . c om*/ try { try (OutputStream out = new FileOutputStream(file)) { out.write("attach2".getBytes()); } final DataSource dataSource = new DataSource() { @Override public OutputStream getOutputStream() throws IOException { return null; } @Override public String getName() { return "name3.txt"; } @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream("attach3".getBytes()); } @Override public String getContentType() { return "text/plain"; } }; long messageId = handler.sendNow("loginId", "messageName", "from@addr", asList("to@addr"), asList("cc@addr"), asList("bcc@addr"), "subject", "body", new AttachmentPreparator() { @Override public void prepare(Attachment attachment) throws MessagingException { attachment.add("name0.txt", new ByteArrayResource("attach0".getBytes())); attachment.add("name1.bin", new ByteArrayResource("attach1".getBytes()), "application/octet-stream"); attachment.add("name2.txt", file); attachment.add("name3.txt", dataSource); } }); Session session = Session.getDefaultInstance(new Properties()); MimeMessage message = new MimeMessage(session); preparator.getValue().prepare(message); assertEquals(0L, messageId); assertEquals(1, message.getRecipients(RecipientType.TO).length); assertEquals(parse("to@addr")[0], message.getRecipients(RecipientType.TO)[0]); assertEquals(1, message.getRecipients(RecipientType.CC).length); assertEquals(parse("cc@addr")[0], message.getRecipients(RecipientType.CC)[0]); assertEquals(1, message.getRecipients(RecipientType.BCC).length); assertEquals(parse("bcc@addr")[0], message.getRecipients(RecipientType.BCC)[0]); assertEquals(1, message.getFrom().length); assertEquals(parse("from@addr")[0], message.getFrom()[0]); assertEquals("subject", message.getSubject()); MimeMultipart mm = (MimeMultipart) message.getContent(); assertEquals(5, mm.getCount()); assertEquals("body", ((MimeMultipart) mm.getBodyPart(0).getContent()).getBodyPart(0).getContent()); assertEquals("name0.txt", mm.getBodyPart(1).getFileName()); assertEquals("text/plain", mm.getBodyPart(1).getContentType()); assertEquals("attach0", mm.getBodyPart(1).getContent()); assertEquals("name1.bin", mm.getBodyPart(2).getDataHandler().getName()); assertEquals("application/octet-stream", mm.getBodyPart(2).getDataHandler().getContentType()); assertEquals("attach1", new String( ByteStreams.toByteArray((InputStream) mm.getBodyPart(2).getDataHandler().getContent()))); assertEquals("name2.txt", mm.getBodyPart(3).getFileName()); assertEquals("text/plain", mm.getBodyPart(3).getContentType()); assertEquals("attach2", mm.getBodyPart(3).getContent()); assertEquals("name3.txt", mm.getBodyPart(4).getFileName()); assertEquals("text/plain", mm.getBodyPart(4).getContentType()); assertEquals("attach3", mm.getBodyPart(4).getContent()); } finally { file.delete(); } }
From source file:com.basp.trabajo_al_minuto.model.business.BusinessUtils.java
/** * Se encarga de enviar el mensaje de correo electronico * *//*www. j av a 2 s . c om*/ public static Boolean sendEmail(final EmailMessage emdto) throws BusinessException { try { Session session; Properties properties = System.getProperties(); properties.put("mail.host", emdto.getHost()); properties.put("mail.transport.protocol", "smtp"); properties.put("mail.smtp.port", emdto.getPort()); properties.put("mail.smtp.starttls.enable", emdto.getStarttls()); if (emdto.getUser() != null && emdto.getPassword() != null) { properties.put("mail.smtp.auth", "true"); session = Session.getDefaultInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(emdto.getUser(), emdto.getPassword()); } }); } else { properties.put("mail.smtp.auth", "false"); session = Session.getDefaultInstance(properties); } message = new MimeMessage(session); message.setFrom(new InternetAddress(emdto.getFrom(), emdto.getMask())); message.setSubject(emdto.getSubject()); for (String to : emdto.getToList()) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } if (emdto.getCcList() != null) { for (String cc : emdto.getCcList()) { message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc)); } } if (emdto.getCcoList() != null) { for (String cco : emdto.getCcoList()) { message.addRecipient(Message.RecipientType.BCC, new InternetAddress(cco)); } } bodyPart = new MimeBodyPart(); bodyPart.setContent(emdto.getBodyMessage(), emdto.getMimeTypeMessage()); multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (emdto.getFilePaths() != null) { for (String filePath : emdto.getFilePaths()) { File file = new File(filePath); if (file.exists()) { dataSource = new FileDataSource(file); bodyPart = new MimeBodyPart(); bodyPart.setDataHandler(new DataHandler(dataSource)); bodyPart.setFileName(file.getName()); multipart.addBodyPart(bodyPart); } } } message.setContent(multipart); Transport.send(message); } catch (MessagingException | UnsupportedEncodingException ex) { Logger.getLogger(BusinessUtils.class.getName()).log(Level.SEVERE, "BusinessUtils.sendEmail Exception", ex); throw new BusinessException(ex); } return Boolean.TRUE; }
From source file:com.nokia.helium.core.EmailDataSender.java
/** * Send xml data//from w w w . ja v a 2 s . c o m * * @param String purpose of this email * @param String file to send * @param String mime type * @param String subject of email * @param String header of mail * @param boolean compress data if true */ public void sendData(String purpose, File fileToSend, String mimeType, String subject, String header, boolean compressData) throws EmailSendException { try { log.debug("sendData:Send file: " + fileToSend + " and mimetype: " + mimeType); if (fileToSend != null && fileToSend.exists()) { InternetAddress[] toAddresses = getToAddressList(); Properties props = new Properties(); if (smtpServerAddress != null) { log.debug("sendData:smtp address: " + smtpServerAddress); props.setProperty("mail.smtp.host", smtpServerAddress); } Session mailSession = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(mailSession); message.setSubject(subject == null ? "" : subject); MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); ByteArrayDataSource dataSrc = null; String fileName = fileToSend.getName(); if (compressData) { log.debug("Sending compressed data"); dataSrc = compressFile(fileToSend); dataSrc.setName(fileName + ".gz"); messageBodyPart.setFileName(fileName + ".gz"); } else { log.debug("Sending uncompressed data:"); dataSrc = new ByteArrayDataSource(new FileInputStream(fileToSend), mimeType); message.setContent(FileUtils.readFileToString(fileToSend), "text/html"); multipart = null; } String headerToSend = null; if (header == null) { headerToSend = ""; } messageBodyPart.setHeader("helium-bld-data", headerToSend); messageBodyPart.setDataHandler(new DataHandler(dataSrc)); if (multipart != null) { multipart.addBodyPart(messageBodyPart); // add to the // multipart message.setContent(multipart); } try { message.setFrom(getFromAddress()); } catch (AddressException e) { throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e); } catch (LDAPException e) { throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e); } message.addRecipients(Message.RecipientType.TO, toAddresses); log.info("Sending email alert: " + subject); Transport.send(message); } } catch (MessagingException e) { String fullErrorMessage = "Failed sending e-mail: " + purpose; if (e.getMessage() != null) { fullErrorMessage += ": " + e.getMessage(); } throw new EmailSendException(fullErrorMessage, e); } catch (IOException e) { String fullErrorMessage = "Failed sending e-mail: " + purpose; if (e.getMessage() != null) { fullErrorMessage += ": " + e.getMessage(); } // We are Ignoring the errors as no need to fail the build. throw new EmailSendException(fullErrorMessage, e); } }
From source file:atd.backend.Register.java
public void sendRegMail(Klant k) throws IOException { Properties propMail = new Properties(); InputStream config = null;// w w w .j av a 2s . c o m config = new URL(CONFIG_URL).openStream(); propMail.load(config); Properties props = new Properties(); props.put("mail.smtp.host", propMail.getProperty("host")); props.put("mail.smtp.port", 465); props.put("mail.smtp.ssl.enable", true); Session mailSession = Session.getInstance(props); try { Logger.getLogger("atd.log").info("Stuurt mail naar: " + k.getEmail()); MimeMessage msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress(propMail.getProperty("email"), propMail.getProperty("mailName"))); msg.setRecipients(Message.RecipientType.TO, k.getEmail()); msg.setSubject("Uw account is aangemaakt"); msg.setSentDate(Calendar.getInstance().getTime()); msg.setContent("Beste " + k.getNaam() + ", \n\nUw account " + k.getUsername() + " is aangemaakt, U kunt inloggen op de <a href='https://atd.plebian.nl'>ATD website</a>\n", "text/html; charset=utf-8"); // TODO: Heeft OAUTH nodig, maarja we zijn al niet erg netjes met // wachtwoorden Transport.send(msg, propMail.getProperty("email"), propMail.getProperty("password")); } catch (Exception e) { Logger.getLogger("atd.log").warning("send failed: " + e.getMessage()); } }
From source file:com.threewks.thundr.gmail.GmailMailer.java
/** * Create a MimeMessage using the parameters provided. * * @param to Email address of the receiver. * @param from Email address of the sender, the mailbox account. * @param subject Subject of the email. * @param bodyText Body text of the email. * @return MimeMessage to be used to send email. * @throws MessagingException/*from w w w . j av a 2s . co m*/ */ protected MimeMessage createEmailWithAttachment(Set<InternetAddress> to, InternetAddress from, Set<InternetAddress> cc, Set<InternetAddress> bcc, InternetAddress replyTo, String subject, String bodyText, List<com.threewks.thundr.mail.Attachment> attachments) { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); try { email.setFrom(from); if (to != null) { email.addRecipients(javax.mail.Message.RecipientType.TO, to.toArray(new InternetAddress[to.size()])); } if (cc != null) { email.addRecipients(javax.mail.Message.RecipientType.CC, cc.toArray(new InternetAddress[cc.size()])); } if (bcc != null) { email.addRecipients(javax.mail.Message.RecipientType.BCC, bcc.toArray(new InternetAddress[bcc.size()])); } if (replyTo != null) { email.setReplyTo(new Address[] { replyTo }); } email.setSubject(subject); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(bodyText, "text/html"); mimeBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\""); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); if (attachments != null) { for (com.threewks.thundr.mail.Attachment attachment : attachments) { mimeBodyPart = new MimeBodyPart(); BasicViewRenderer renderer = new BasicViewRenderer(viewResolverRegistry); renderer.render(attachment.view()); byte[] data = renderer.getOutputAsBytes(); String attachmentContentType = renderer.getContentType(); String attachmentCharacterEncoding = renderer.getCharacterEncoding(); populateMimeBodyPart(mimeBodyPart, attachment, data, attachmentContentType, attachmentCharacterEncoding); multipart.addBodyPart(mimeBodyPart); } } email.setContent(multipart); } catch (MessagingException e) { Logger.error(e.getMessage()); Logger.error( "Failed to create email from: %s;%s, to: %s, cc: %s, bcc: %s, replyTo %s;%s, subject %s, body %s, number of attachments %d", from.getAddress(), from.getPersonal(), Transformers.InternetAddressesToString.from(to), Transformers.InternetAddressesToString.from(cc), Transformers.InternetAddressesToString.from(bcc), replyTo == null ? "null" : replyTo.getAddress(), replyTo == null ? "null" : replyTo.getPersonal(), subject, bodyText, attachments == null ? 0 : attachments.size()); throw new GmailException(e); } return email; }