List of usage examples for javax.mail.internet MimeMessage MimeMessage
public MimeMessage(MimeMessage source) throws MessagingException
source
MimeMessage. From source file:TestOpenMailRelay.java
/** Do the work: send the mail to the SMTP server. */ public void doSend() { // We need to pass info to the mail server as a Properties, since // JavaMail (wisely) allows room for LOTS of properties... Properties props = new Properties(); // Your LAN must define the local SMTP server as "mailhost" // for this simple-minded version to be able to send mail... props.put("mail.smtp.host", "mailhost"); // Create the Session object session = Session.getDefaultInstance(props, null); session.setDebug(true); // Verbose! try {/*from ww w.j a va2 s .co m*/ // create a message mesg = new MimeMessage(session); // From Address - this should come from a Properties... mesg.setFrom(new InternetAddress("nobody@host.domain")); // TO Address InternetAddress toAddress = new InternetAddress(message_recip); mesg.addRecipient(Message.RecipientType.TO, toAddress); // CC Address InternetAddress ccAddress = new InternetAddress(message_cc); mesg.addRecipient(Message.RecipientType.CC, ccAddress); // The Subject mesg.setSubject(message_subject); // Now the message body. mesg.setText(message_body); // XXX I18N: use setText(msgText.getText(), charset) // Finally, send the message! Transport.send(mesg); } catch (MessagingException ex) { while ((ex = (MessagingException) ex.getNextException()) != null) { ex.printStackTrace(); } } }
From source file:mitm.application.djigzo.james.mailets.RequestSenderCertificateTest.java
@Test public void testRequestCertificatePendingAvailableSkipIfAvailableFalse() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig(); String from = "from@example.com"; String to = "to@example.com"; proxy.addCertificateRequest(from);/*from ww w. j a va 2 s . c o m*/ RequestSenderCertificate mailet = new RequestSenderCertificate(); mailetConfig.setInitParameter("skipIfAvailable", "false"); mailet.init(mailetConfig); MockMail mail = new MockMail(); MimeMessage message = new MimeMessage(MailSession.getDefaultSession()); message.setContent("test", "text/plain"); message.setFrom(new InternetAddress(from)); message.saveChanges(); mail.setMessage(message); Collection<MailAddress> recipients = new LinkedList<MailAddress>(); recipients.add(new MailAddress(to)); mail.setRecipients(recipients); mail.setSender(new MailAddress("somethingelse@example.com")); assertFalse(proxy.isUser(from)); assertFalse(proxy.isUser(to)); mailet.service(mail); assertEquals(INITIAL_KEY_STORE_SIZE + 1, proxy.getKeyAndCertStoreSize()); assertFalse(proxy.isUser(to)); assertTrue(proxy.isUser(from)); }
From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java
@Test public void testProcessEmailHtmlText() throws MessagingException, IOException { MessageListener mockListener1 = mock(MessageListener.class); when(mockListener1.getComponentId()).thenReturn("componentId"); when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE); MessageListener mockListener2 = mock(MessageListener.class); Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2); listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1); listenersByEmail.put("theflanders@silverpeas.com", 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("Simple html Email test"); String html = loadHtml();/* w ww . j a v a 2 s . c om*/ mail.setText(html, "UTF-8", "html"); mail.setSentDate(new Date()); Date sentDate = new Date(mail.getSentDate().getTime()); Transport.send(mail); Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>(); messageChecker.processEmail(mail, events, listenersByEmail); assertNotNull(events); assertEquals(1, events.size()); assertNull(events.get(mockListener2)); MessageEvent event = events.get(mockListener1); assertNotNull(event); assertNotNull(event.getMessages()); assertEquals(1, event.getMessages().size()); Message message = event.getMessages().get(0); assertEquals("bart.simpson@silverpeas.com", message.getSender()); assertEquals("Simple html Email test", message.getTitle()); assertEquals(html, message.getBody()); assertNotNull(message.getSentDate()); assertEquals(sentDate.getTime(), message.getSentDate().getTime()); assertEquals(htmlEmailSummary, message.getSummary()); assertEquals(0, message.getAttachmentsSize()); assertEquals(0, message.getAttachments().size()); assertEquals("componentId", message.getComponentId()); assertEquals("text/html; charset=UTF-8", message.getContentType()); verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com"); }
From source file:it.eng.spagobi.tools.scheduler.dispatcher.MailDocumentDispatchChannel.java
public boolean dispatch(BIObject document, byte[] executionOutput) { Map parametersMap;// w ww . ja va 2s . c o m String contentType; String fileExtension; IDataStore emailDispatchDataStore; String nameSuffix; String descriptionSuffix; String containedFileName; String zipFileName; boolean reportNameInSubject; logger.debug("IN"); try { parametersMap = dispatchContext.getParametersMap(); contentType = dispatchContext.getContentType(); fileExtension = dispatchContext.getFileExtension(); emailDispatchDataStore = dispatchContext.getEmailDispatchDataStore(); nameSuffix = dispatchContext.getNameSuffix(); descriptionSuffix = dispatchContext.getDescriptionSuffix(); containedFileName = dispatchContext.getContainedFileName() != null && !dispatchContext.getContainedFileName().equals("") ? dispatchContext.getContainedFileName() : document.getName(); zipFileName = dispatchContext.getZipMailName() != null && !dispatchContext.getZipMailName().equals("") ? dispatchContext.getZipMailName() : document.getName(); reportNameInSubject = dispatchContext.isReportNameInSubject(); String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport"); String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL"); logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl); //Custom Trusted Store Certificate Options String trustedStorePath = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.file"); String trustedStorePassword = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.password"); int smptPort = 25; if ((smtphost == null) || smtphost.trim().equals("")) throw new Exception("Smtp host not configured"); if ((smtpport == null) || smtpport.trim().equals("")) { throw new Exception("Smtp host not configured"); } else { smptPort = Integer.parseInt(smtpport); } String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from"); if ((from == null) || from.trim().equals("")) from = "spagobi.scheduler@eng.it"; String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user"); if ((user == null) || user.trim().equals("")) { logger.debug("Smtp user not configured"); user = null; } // throw new Exception("Smtp user not configured"); String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); if ((pass == null) || pass.trim().equals("")) { logger.debug("Smtp password not configured"); } // throw new Exception("Smtp password not configured"); String mailSubj = dispatchContext.getMailSubj(); mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false); String mailTxt = dispatchContext.getMailTxt(); String[] recipients = findRecipients(dispatchContext, document, emailDispatchDataStore); if (recipients == null || recipients.length == 0) { logger.error("No recipients found for email sending!!!"); return false; } //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.port", Integer.toString(smptPort)); // open session Session session = null; // create autheticator object Authenticator auth = null; if (user != null) { auth = new SMTPAuthenticator(user, pass); props.put("mail.smtp.auth", "true"); //SSL Connection if (smtpssl.equals("true")) { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //props.put("mail.smtp.debug", "true"); props.put("mail.smtps.auth", "true"); props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort)); if ((!StringUtilities.isEmpty(trustedStorePath))) { /* Dynamic configuration of trustedstore for CA * Using Custom SSLSocketFactory to inject certificates directly from specified files */ //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY); } else { //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY); } props.put("mail.smtp.socketFactory.fallback", "false"); } //session = Session.getDefaultInstance(props, auth); session = Session.getInstance(props, auth); //session.setDebug(true); //session.setDebugOut(null); logger.info("Session.getInstance(props, auth)"); } else { //session = Session.getDefaultInstance(props); session = Session.getInstance(props); logger.info("Session.getInstance(props)"); } // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type String subject = mailSubj; if (reportNameInSubject) { subject += " " + document.getName() + nameSuffix; } msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(mailTxt + "\n" + descriptionSuffix); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message SchedulerDataSource sds = null; //if zip requested if (dispatchContext.isZipMailDocument()) { mbp2 = zipAttachment(executionOutput, containedFileName, zipFileName, nameSuffix, fileExtension); } //else else { sds = new SchedulerDataSource(executionOutput, contentType, containedFileName + nameSuffix + fileExtension); mbp2.setDataHandler(new DataHandler(sds)); mbp2.setFileName(sds.getName()); } // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message msg.setContent(mp); // send message if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) { //USE SSL Transport comunication with SMTPS Transport transport = session.getTransport("smtps"); transport.connect(smtphost, smptPort, user, pass); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } else { //Use normal SMTP Transport.send(msg); } } catch (Exception e) { logger.error("Error while sending schedule result mail", e); return false; } finally { logger.debug("OUT"); } return true; }
From source file:com.waveerp.sendMail.java
public String sendMsgWithAttach(String strSource, String strSourceDesc, String strSubject, String strMsg, String strDestination, String strDestDesc, String strPath) throws Exception { String strResult = "OK"; // Call the registry management system registrySystem rs = new registrySystem(); // Call the encryption management system desEncryption de = new desEncryption(); de.Encrypter("", ""); String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST"); String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT"); final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER"); String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD"); //Decrypt the encrypted password. final String strPass01 = de.decrypt(strPass); Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", strHost); props.put("mail.smtp.port", strPort); props.put("mail.user", strUser); props.put("mail.password", strPass01); // creates a new session with an authenticator Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(strUser, strPass01); }// ww w .j ava 2 s . co m }; Session session = Session.getInstance(props, auth); // creates a new e-mail message Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(strSource)); //InternetAddress[] toAddresses = { new InternetAddress(strDestination) }; msg.setRecipient(Message.RecipientType.TO, new InternetAddress(strDestination)); msg.setSubject(strSubject); msg.setSentDate(new Date()); // creates message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(strMsg, "text/html"); // creates multi-part Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // adds attachments //if (attachFiles != null && attachFiles.length > 0) { // for (String filePath : attachFiles) { // MimeBodyPart attachPart = new MimeBodyPart(); // // try { // attachPart.attachFile(filePath); // } catch (IOException ex) { // ex.printStackTrace(); // } // // multipart.addBodyPart(attachPart); // } //} String fna; String fnb; URL fileUrl; fileUrl = null; fileUrl = this.getClass().getResource("sendMail.class"); fna = fileUrl.getPath(); fna = fna.substring(0, fna.indexOf("WEB-INF")); //fnb = URLDecoder.decode( fna + TEMP_DIR + strPath ); fnb = URLDecoder.decode(fna + strPath); MimeBodyPart attachPart = new MimeBodyPart(); try { attachPart.attachFile(fnb); } catch (IOException ex) { //ex.printStackTrace(); strResult = ex.getMessage(); } multipart.addBodyPart(attachPart); // sets the multi-part as e-mail's content msg.setContent(multipart); // sends the e-mail Transport.send(msg); return strResult; }
From source file:gmailclientfx.core.GmailClient.java
public static void sendMessage(String to, String subject, String body, List<String> attachments) throws Exception { // authenticate with gmail smtp server SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com", 587, EMAIL, ACCESS_TOKEN, true); // kreiraj MimeMessage objekt MimeMessage msg = new MimeMessage(OAuth2Authenticator.getSession()); // dodaj headere msg.addHeader("Content-type", "text/HTML; charset=UTF-8"); msg.addHeader("format", "flowed"); msg.addHeader("Content-Transfer-Encoding", "8bit"); msg.setFrom(new InternetAddress(EMAIL)); msg.setRecipients(javax.mail.Message.RecipientType.CC, InternetAddress.parse(to)); msg.setSubject(subject, "UTF-8"); msg.setReplyTo(InternetAddress.parse(EMAIL, false)); // tijelo poruke BodyPart msgBodyPart = new MimeBodyPart(); msgBodyPart.setText(body);/* w w w . j av a 2s. c om*/ Multipart multipart = new MimeMultipart(); multipart.addBodyPart(msgBodyPart); msg.setContent(multipart); // dodaj privitke if (attachments.size() > 0) { for (String attachment : attachments) { msgBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachment); msgBodyPart.setDataHandler(new DataHandler(source)); msgBodyPart.setFileName(source.getName()); multipart.addBodyPart(msgBodyPart); } msg.setContent(multipart); } smtpTransport.sendMessage(msg, InternetAddress.parse(to)); Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Poruka poslana!"); alert.setHeaderText(null); alert.setContentText("Email uspjeno poslan!"); alert.showAndWait(); }
From source file:au.org.paperminer.main.UserFilter.java
/** * Sends an email to the user asking they follow a link to validate their email address * @param id DB key to be embedded in response link * @param email Address target//w ww.j a va 2s. c om */ private void sendVerificationEmail(String id, String email, ServletRequest req) { m_logger.debug("sending mail"); String from = "admin@" + m_serverName; Properties props = new Properties(); props.put("mail.smpt.host", m_serverName); props.put("mail.from", from); Session session = Session.getInstance(props, null); try { MimeMessage msg = new MimeMessage(session); msg.setRecipients(Message.RecipientType.TO, email); msg.setSubject("Verify your PaperMiner email address"); msg.setSentDate(new Date()); // FIXME: the verify address needs to be more robust msg.setText("Dear " + email.substring(0, email.indexOf("@")) + ",\n\n" + "PaperMiner has sent you this message to validate that the email address which you " + "supplied is able to receive notifications from our server.\n" + "To complete the verification process, please click the link below.\n\n" + "http://" + m_serverName + ":8080/PaperMiner/pm/vfy?id=" + id + "\n\n" + "If you are unable to click the link above, verification can be completed by copying " + "and pasting it into the address bar of your web browser.\n\n" + "Your email address is " + email + ". Use this to log in when returning to the PaperMiner site.\n" + "You can update your email address, or change your TROVE API key at any time through the " + "\"Manage Your Details\" option of the User menu, but an email change will require re-validation.\n\n" + "Paper Miner Administrator"); Transport.send(msg); m_logger.info("Verifcation mail sent to " + email); } catch (MessagingException ex) { m_logger.error("Email verification to " + email + " failed", ex); req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e109"); } }
From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java
/** * Creates a MIME message (message with binary content carrying capabilities) from an existing Mail * /*from w w w . ja va2 s . co m*/ * @param mail The original Mail object * @param session Mail session * @return The MIME message */ private MimeMessage createMimeMessage(Mail mail, Session session, XWikiContext context) throws MessagingException, XWikiException, IOException { // this will also check for email error InternetAddress from = new InternetAddress(mail.getFrom()); String recipients = mail.getHeader("To"); if (StringUtils.isBlank(recipients)) { recipients = mail.getTo(); } else { recipients = mail.getTo() + "," + recipients; } InternetAddress[] to = toInternetAddresses(recipients); recipients = mail.getHeader("Cc"); if (StringUtils.isBlank(recipients)) { recipients = mail.getCc(); } else { recipients = mail.getCc() + "," + recipients; } InternetAddress[] cc = toInternetAddresses(recipients); recipients = mail.getHeader("Bcc"); if (StringUtils.isBlank(recipients)) { recipients = mail.getBcc(); } else { recipients = mail.getBcc() + "," + recipients; } InternetAddress[] bcc = toInternetAddresses(recipients); if ((to == null) && (cc == null) && (bcc == null)) { LOGGER.info("No recipient -> skipping this email"); return null; } MimeMessage message = new MimeMessage(session); message.setSentDate(new Date()); message.setFrom(from); if (to != null) { message.setRecipients(javax.mail.Message.RecipientType.TO, to); } if (cc != null) { message.setRecipients(javax.mail.Message.RecipientType.CC, cc); } if (bcc != null) { message.setRecipients(javax.mail.Message.RecipientType.BCC, bcc); } message.setSubject(mail.getSubject(), EMAIL_ENCODING); for (Map.Entry<String, String> header : mail.getHeaders().entrySet()) { message.setHeader(header.getKey(), header.getValue()); } if (mail.getHtmlPart() != null || mail.getAttachments() != null) { Multipart multipart = createMimeMultipart(mail, context); message.setContent(multipart); } else { message.setText(mail.getTextPart()); } message.setSentDate(new Date()); message.saveChanges(); return message; }
From source file:mitm.application.djigzo.james.matchers.HasValidPasswordTest.java
@Test public void testMultipleMatches() throws MessagingException, EncryptorException { HasValidPassword matcher = new HasValidPassword(); MockMatcherConfig matcherConfig = new MockMatcherConfig("test", "matchOnError=false", mailetContext); matcher.init(matcherConfig);//from w w w . j a v a 2s. c o m Mail mail = new MockMail(); MimeMessage message = new MimeMessage(MailSession.getDefaultSession()); message.setContent("test", "text/plain"); message.setFrom(new InternetAddress("123456@example.com")); message.saveChanges(); mail.setMessage(message); Collection<MailAddress> recipients = new LinkedList<MailAddress>(); recipients.add(new MailAddress("test2@example.com")); recipients.add(new MailAddress("test5@example.com")); mail.setRecipients(recipients); Collection<?> result = matcher.match(mail); assertEquals(2, result.size()); assertTrue(result.contains(new MailAddress("test2@example.com"))); assertTrue(result.contains(new MailAddress("test5@example.com"))); DjigzoMailAttributes attributes = new DjigzoMailAttributesImpl(mail); Passwords passwords = attributes.getPasswords(); assertNotNull(passwords); assertNotNull(passwords.get("test2@example.com")); assertEquals("test2", passwords.get("test2@example.com").getPassword()); assertEquals("ID2", passwords.get("test2@example.com").getPasswordID()); assertNotNull(passwords.get("test5@example.com")); assertEquals("test5", passwords.get("test5@example.com").getPassword()); assertEquals("ID5", passwords.get("test5@example.com").getPasswordID()); }
From source file:io.uengine.mail.MailAsyncService.java
@Async public void sendBySmtp(String subject, String text, String fromUser, String fromName, final String toUser, String telephone, InternetAddress[] toCC) { Session session = setMailProperties(toUser); Map<String, Object> model = new HashMap<>(); model.put("subject", subject); model.put("message", text); model.put("name", fromName); model.put("email", fromUser); model.put("telephone", telephone); String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/contactus.vm", "UTF-8", model);/*from w ww . j a v a2s . c o m*/ try { InternetAddress from = new InternetAddress(fromUser, fromName); Message message = new MimeMessage(session); message.setFrom(from); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser)); message.setSubject(subject); // message.setText(text); message.setContent(body, "text/html;charset=utf-8"); if (toCC != null && toCC.length > 0) message.setRecipients(Message.RecipientType.CC, toCC); Transport.send(message); logger.info("{} ? ?? .", toUser); } catch (Exception e) { throw new ServiceException("?? .", e); } }