List of usage examples for javax.mail.internet MimeMessage MimeMessage
public MimeMessage(MimeMessage source) throws MessagingException
source
MimeMessage. From source file:it.infn.ct.security.actions.RegisterUser.java
private void sendMail(UserRequest usreq) throws MailException { javax.mail.Session session = null;/*from w ww . ja va 2 s . c o m*/ try { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); session = (javax.mail.Session) envCtx.lookup("mail/Users"); } catch (Exception ex) { log.error("Mail resource lookup error"); log.error(ex.getMessage()); throw new MailException("Mail Resource not available"); } Message mailMsg = new MimeMessage(session); try { mailMsg.setFrom(new InternetAddress(mailFrom, idPAdmin)); InternetAddress mailTo[] = new InternetAddress[1]; mailTo[0] = new InternetAddress(usreq.getPreferredMail(), usreq.getTitle() + " " + usreq.getGivenname() + " " + usreq.getSurname()); mailMsg.setRecipients(Message.RecipientType.TO, mailTo); String ccMail[] = mailCC.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); mailMsg.setSubject(mailSubject); mailBody = mailBody.replaceAll("_USER_", usreq.getTitle() + " " + usreq.getGivenname() + " " + usreq.getSurname()); mailMsg.setText(mailBody); Transport.send(mailMsg); } catch (UnsupportedEncodingException ex) { log.error(ex); throw new MailException("Mail from address format not valid"); } catch (MessagingException ex) { log.error(ex); throw new MailException("Mail message has problems"); } }
From source file:com.vaushell.superpipes.dispatch.ErrorMailer.java
private void sendHTML(final String message) throws MessagingException, IOException { if (message == null || message.isEmpty()) { throw new IllegalArgumentException("message"); }//from w w w. ja v a 2 s . com final String host = properties.getConfigString("host"); final Properties props = System.getProperties(); props.setProperty("mail.smtp.host", host); final String port = properties.getConfigString("port", null); if (port != null) { props.setProperty("mail.smtp.port", port); } if ("true".equalsIgnoreCase(properties.getConfigString("ssl", null))) { props.setProperty("mail.smtp.ssl.enable", "true"); } final Session session = Session.getInstance(props, null); // session.setDebug( true ); final javax.mail.Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(properties.getConfigString("from"))); msg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(properties.getConfigString("to"), false)); msg.setSubject("superpipes error message"); msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message, "text/html"))); msg.setHeader("X-Mailer", "superpipes"); Transport t = null; try { t = session.getTransport("smtp"); final String username = properties.getConfigString("username", null); final String password = properties.getConfigString("password", null); if (username == null || password == null) { t.connect(); } else { if (port == null || port.isEmpty()) { t.connect(host, username, password); } else { t.connect(host, Integer.parseInt(port), username, password); } } t.sendMessage(msg, msg.getAllRecipients()); } finally { if (t != null) { t.close(); } } }
From source file:eu.openanalytics.rsb.component.EmailDepositHandlerTestCase.java
@Test public void handleResult() throws Exception { final Map<String, Serializable> meta = new HashMap<String, Serializable>(); meta.put(EmailDepositHandler.EMAIL_ADDRESSEE_META_NAME, "addressee@test.com"); meta.put(EmailDepositHandler.EMAIL_REPLY_TO_META_NAME, "replyto@test.com"); meta.put(EmailDepositHandler.EMAIL_REPLY_CC_META_NAME, new String[] { "replyCC@test.com" }); meta.put(EmailDepositHandler.EMAIL_SUBJECT_META_NAME, "subject"); meta.put(EmailDepositHandler.EMAIL_BODY_META_NAME, "your result"); final MultiFilesResult multiFilesResult = mock(MultiFilesResult.class); when(multiFilesResult.isSuccess()).thenReturn(true); when(multiFilesResult.getApplicationName()).thenReturn(TEST_APPLICATION_NAME); when(multiFilesResult.getTemporaryDirectory()).thenReturn(FileUtils.getTempDirectory()); when(multiFilesResult.getMeta()).thenReturn(meta); final URL jobFakingAResult = Thread.currentThread().getContextClassLoader() .getResource("data/r-job-sample.zip"); when(multiFilesResult.getPayload()).thenReturn(new File[] { new File(jobFakingAResult.toURI()) }); when(mailSender.createMimeMessage()).thenReturn(new MimeMessage((Session) null)); emailDepositHandler.handleResult(multiFilesResult); @SuppressWarnings("rawtypes") final ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class); verify(outboundEmailChannel).send(messageCaptor.capture()); @SuppressWarnings("unchecked") final Message<MimeMailMessage> message = messageCaptor.getValue(); final MimeMessage mimeMessage = message.getPayload().getMimeMessage(); assertThat(mimeMessage.getSubject(), is("RE: subject")); }
From source file:com.bia.gmailjava.EmailService.java
/** * * @param addressTo/*w w w. j a v a 2 s . com*/ * @param subject * @param message * @throws AddressException * @throws MessagingException */ private void send(InternetAddress[] addressTo, String subject, String message) throws AddressException, MessagingException { Message msg = new MimeMessage(createSession()); InternetAddress addressFrom = new InternetAddress(USERNAME); msg.setFrom(addressFrom); msg.setRecipients(Message.RecipientType.TO, addressTo); // set bcc //InternetAddress[] bcc1 = getBCC(); //msg.setRecipients(Message.RecipientType.BCC, bcc1); // Setting the Subject and Content Type msg.setSubject(subject); //String message = comment; msg.setContent(message, EMAIL_CONTENT_TYPE); Transport.send(msg); }
From source file:br.com.cgcop.administrativo.modelo.ContaEmail.java
public void enviarEmailHtml(List<String> destinos, String msg, String titulo) { // Recipient's email ID needs to be mentioned. String to = ""; String rodape = "<br/><br/><br/><br/> <div style=\"border-top: 1px dashed #c8cdbe;border-top: 1px dashed #c8cdbe \">" + "Esta mensagem uma notificao enviada automaticamente por tanto no deve ser respondida. <br/> " + "<span style=\"font-style: italic; font-family: Narrow; font-size: large; color: rgb(0, 153, 0);\">Sistema de Gesto de Projetos e Obras - SGPO</span><br/>" + "<span style=\"font-size: large; font-style: italic; color: rgb(0, 153, 0); font-family: Narrow;\">Oiti Engenharia e Gesto Ambiental</span>" + "</div>"; for (String d : destinos) { if (d.equals(destinos.get(destinos.size() - 1))) { to = to.concat(d);/*from w w w.j a v a 2 s. co m*/ } else { to = to.concat(d.concat(",")); } } // Sender's email ID needs to be mentioned String from = this.email; final String username = this.email;//change accordingly final String password = this.senha;//change accordingly Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", this.host); props.put("mail.smtp.port", "25"); // Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. Message message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set Subject: header field message.setSubject(titulo); // Send the actual HTML message, as big as you like message.setContent(msg + rodape, "text/html"); // Send message Transport.send(message); } catch (MessagingException e) { e.printStackTrace(); throw new RuntimeException(e); } }
From source file:com.cws.esolutions.core.utils.EmailUtils.java
/** * Processes and sends an email message as generated by the requesting * application. This method is utilized with a JNDI datasource. * * @param mailConfig - The {@link com.cws.esolutions.core.config.xml.MailConfig} to utilize * @param message - The email message/* w w w . j a va2 s.c o m*/ * @param isWeb - <code>true</code> if this came from a container, <code>false</code> otherwise * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs sending the message */ public static final synchronized void sendEmailMessage(final MailConfig mailConfig, final EmailMessage message, final boolean isWeb) throws MessagingException { final String methodName = EmailUtils.CNAME + "#sendEmailMessage(final MailConfig mailConfig, final EmailMessage message, final boolean isWeb) throws MessagingException"; Session mailSession = null; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", mailConfig); DEBUGGER.debug("Value: {}", message); DEBUGGER.debug("Value: {}", isWeb); } SMTPAuthenticator smtpAuth = null; if (DEBUG) { DEBUGGER.debug("MailConfig: {}", mailConfig); } try { if (isWeb) { Context initContext = new InitialContext(); Context envContext = (Context) initContext.lookup(EmailUtils.INIT_DS_CONTEXT); if (DEBUG) { DEBUGGER.debug("InitialContext: {}", initContext); DEBUGGER.debug("Context: {}", envContext); } if (envContext != null) { mailSession = (Session) envContext.lookup(mailConfig.getDataSourceName()); } } else { Properties mailProps = new Properties(); try { mailProps.load( EmailUtils.class.getClassLoader().getResourceAsStream(mailConfig.getPropertyFile())); } catch (NullPointerException npx) { try { mailProps.load(new FileInputStream(mailConfig.getPropertyFile())); } catch (IOException iox) { throw new MessagingException(iox.getMessage(), iox); } } catch (IOException iox) { throw new MessagingException(iox.getMessage(), iox); } if (DEBUG) { DEBUGGER.debug("Properties: {}", mailProps); } if (StringUtils.equals((String) mailProps.get("mail.smtp.auth"), "true")) { smtpAuth = new SMTPAuthenticator(); mailSession = Session.getDefaultInstance(mailProps, smtpAuth); } else { mailSession = Session.getDefaultInstance(mailProps); } } if (DEBUG) { DEBUGGER.debug("Session: {}", mailSession); } if (mailSession == null) { throw new MessagingException("Unable to configure email services"); } mailSession.setDebug(DEBUG); MimeMessage mailMessage = new MimeMessage(mailSession); // Our emailList parameter should contain the following // items (in this order): // 0. Recipients // 1. From Address // 2. Generated-From (if blank, a default value is used) // 3. The message subject // 4. The message content // 5. The message id (optional) // We're only checking to ensure that the 'from' and 'to' // values aren't null - the rest is really optional.. if // the calling application sends a blank email, we aren't // handing it here. if (message.getMessageTo().size() != 0) { for (String to : message.getMessageTo()) { if (DEBUG) { DEBUGGER.debug(to); } mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); } mailMessage.setFrom(new InternetAddress(message.getEmailAddr().get(0))); mailMessage.setSubject(message.getMessageSubject()); mailMessage.setContent(message.getMessageBody(), "text/html"); if (message.isAlert()) { mailMessage.setHeader("Importance", "High"); } Transport mailTransport = mailSession.getTransport("smtp"); if (DEBUG) { DEBUGGER.debug("Transport: {}", mailTransport); } mailTransport.connect(); if (mailTransport.isConnected()) { Transport.send(mailMessage); } } } catch (MessagingException mex) { throw new MessagingException(mex.getMessage(), mex); } catch (NamingException nx) { throw new MessagingException(nx.getMessage(), nx); } }
From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java
public static void SendEmailPassed(String from, String to1, String subject, String filename) throws FileNotFoundException, IOException { try {/* w w w . java 2 s . co m*/ //Get properties object Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); //get Session Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, "anda.cristea"); } }); //compose message try { MimeMessage message = new MimeMessage(session); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1)); //message.addRecipient(Message.RecipientType.BCC, new InternetAddress(grupSephora)); message.setSubject(subject); // message.setText(msg); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("Raport teste automate"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); //send message Transport.send(message); System.out.println("message sent successfully"); } catch (Exception ex) { System.out.println("eroare trimitere email-uri"); System.out.println(ex.getMessage()); } } catch (Exception ex) { System.out.println("eroare trimitere email-uri"); System.out.println(ex.getMessage()); } }
From source file:com.silverpeas.mailinglist.service.notification.AdvancedNotificationHelperTest.java
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);/* w w w . j a v a 2s.c o 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:mitm.application.djigzo.james.matchers.HasValidPasswordTest.java
@Test public void testNullDatePasswordSet() throws MessagingException, EncryptorException { HasValidPassword matcher = new HasValidPassword(); MockMatcherConfig matcherConfig = new MockMatcherConfig("test", "matchOnError=false", mailetContext); matcher.init(matcherConfig);/*from ww w . j a va2 s . co 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("test6@example.com")); mail.setRecipients(recipients); Collection<?> result = matcher.match(mail); assertEquals(1, result.size()); }
From source file:edu.harvard.iq.dataverse.MailServiceBean.java
public void sendMail(String from, String to, String subject, String messageText, Map<Object, Object> extraHeaders) { try {// ww w.ja v a 2 s . c om MimeMessage msg = new MimeMessage(session); if (from.matches(EMAIL_PATTERN)) { msg.setFrom(new InternetAddress(from)); } else { // set fake from address; instead, add it as part of the message //msg.setFrom(new InternetAddress("invalid.email.address@mailinator.com")); msg.setFrom(getSystemAddress()); messageText = "From: " + from + "\n\n" + messageText; } msg.setSentDate(new Date()); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); msg.setSubject(subject, charset); msg.setText(messageText, charset); if (extraHeaders != null) { for (Object key : extraHeaders.keySet()) { String headerName = key.toString(); String headerValue = extraHeaders.get(key).toString(); msg.addHeader(headerName, headerValue); } } Transport.send(msg); } catch (AddressException ae) { ae.printStackTrace(System.out); } catch (MessagingException me) { me.printStackTrace(System.out); } }