List of usage examples for javax.mail.internet MimeMessage MimeMessage
public MimeMessage(MimeMessage source) throws MessagingException
source
MimeMessage. From source file:mitm.common.mail.filter.UnsupportedFormatStripper.java
private MimeMessage buildMessage(MimeMessage source, PartsContext context) throws MessagingException, IOException { List<Part> parts = context.getParts(); assert (parts.size() > 0); MimeMessage newMessage;//from w w w .ja v a 2 s .c o m if (parts.size() > 1) { /* there is more than one S/MIME part so we need to create a multipart message */ Multipart mp = new MimeMultipart(); for (Part part : parts) { MimeBodyPart bodyPart = BodyPartUtils.toMimeBodyPart(part); mp.addBodyPart(bodyPart); } newMessage = new MimeMessage(MailSession.getDefaultSession()); newMessage.setContent(mp); } else { newMessage = BodyPartUtils.toMessage(parts.get(0), true /* clone */); } copyNonContentHeaders(source, newMessage); return newMessage; }
From source file:net.timbusproject.extractors.pojo.CallBack.java
public void sendEmail(String to, String subject, String body) { final String fromUser = fromMail; final String passUser = password; Properties props = new Properties(); props.put("mail.smtp.host", smtp); props.put("mail.smtp.socketFactory.port", port); props.put("mail.smtp.socketFactory.class", socketFactoryClass); props.put("mail.smtp.auth", mailAuth); props.put("mail.smtp.port", port); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(fromUser, passUser); }//from w w w. java 2 s . c o m }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromUser)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(subject); message.setText(body); Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:mitm.application.djigzo.james.mailets.RequestSenderCertificateTest.java
@Test public void testRequestCertificateSigningCertAvailable() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig(); String from = "test@example.com"; String to = "to@example.com"; KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12"); keyStore.load(new FileInputStream("test/resources/testdata/keys/testCertificates.p12"), "test".toCharArray()); SystemServices.getKeyAndCertificateWorkflow().importKeyStore(keyStore, MissingKey.ADD_CERTIFICATE); assertEquals(22, proxy.getKeyAndCertStoreSize()); RequestSenderCertificate mailet = new RequestSenderCertificate(); mailet.init(mailetConfig);/*from w w w.ja v a 2 s .co m*/ 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(22, proxy.getKeyAndCertStoreSize()); assertFalse(proxy.isUser(to)); assertFalse(proxy.isUser(from)); }
From source file:com.app.mail.DefaultMailSender.java
private Message _populatePasswordResetToken(String emailAddress, String passwordResetToken, Session session) throws Exception { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(PropertiesValues.OUTBOUND_EMAIL_ADDRESS, "Auction Alert")); message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress)); message.setSubject("Password Reset Token"); Map<String, Object> rootMap = new HashMap<>(); rootMap.put("passwordResetToken", passwordResetToken); rootMap.put("rootDomainName", PropertiesValues.ROOT_DOMAIN_NAME); String messageBody = VelocityEngineUtils.mergeTemplateIntoString(_velocityEngine, "template/password_token.vm", "UTF-8", rootMap); message.setContent(messageBody, "text/html"); return message; }
From source file:mitm.application.djigzo.james.mailets.BlackberrySMIMEAdapter.java
private void createMessageFromTemplate(Mail mail) throws MessagingException, MissingRecipientsException, TemplateException, IOException, PartException { SimpleHash root = new SimpleHash(); /*/* w ww .j a va2s . co m*/ * Create a message from a template */ MimeMessage containerMessage = createMessage(mail, root); /* * Copy all non content headers from source to destination */ HeaderMatcher nonContentMatcher = new NotHeaderNameMatcher(new ContentHeaderNameMatcher()); HeaderUtils.copyHeaders(mail.getMessage(), containerMessage, nonContentMatcher); /* * We now need to replace the s/mime attachment from the template with the real attachment */ replaceSMIMEAttachment(containerMessage, mail.getMessage()); containerMessage.saveChanges(); /* * A new MimeMessage instance will be created. This makes ure that the * MimeMessage can be written by James (using writeTo()). */ mail.setMessage(new MimeMessage(containerMessage)); }
From source file:davmail.smtp.TestSmtp.java
public void testSendPlainTextMessage() throws IOException, MessagingException, InterruptedException { String body = "Test plain text message"; MimeMessage mimeMessage = new MimeMessage((Session) null); mimeMessage.addHeader("To", Settings.getProperty("davmail.to")); mimeMessage.setSubject("Test text/plain message"); mimeMessage.setText(body);//from ww w . ja va2 s . co m sendAndCheckMessage(mimeMessage); }
From source file:javamailclient.GmailAPI.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./*from ww w .j a v a 2s.co m*/ * @param bodyText Body text of the email. * @param fileDir Path to the directory containing attachment. * @param filename Name of file to be attached. * @return MimeMessage to be used to send email. * @throws MessagingException */ public static MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText, String fileDir, String filename) throws MessagingException, IOException { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); InternetAddress tAddress = new InternetAddress(to); InternetAddress fAddress = new InternetAddress(from); email.setFrom(fAddress); email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress); email.setSubject(subject); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(bodyText, "text/plain"); mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\""); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); mimeBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(fileDir + filename); mimeBodyPart.setDataHandler(new DataHandler(source)); mimeBodyPart.setFileName(filename); String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename)); mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\""); mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64"); multipart.addBodyPart(mimeBodyPart); email.setContent(multipart); return email; }
From source file:esg.node.components.notification.ESGNotifier.java
private boolean sendNotification(String userid, String userAddress, String messageText) { Message msg = null;/* w ww. j ava2 s. com*/ boolean success = false; String myAddress = null; try { msg = new MimeMessage(session); msg.setHeader("X-Mailer", "ESG DataNode IshMailer"); msg.setSentDate(new Date()); myAddress = props.getProperty("mail.admin.address", "esg-admin@llnl.gov"); msg.setFrom(new InternetAddress(myAddress)); msg.setSubject(subject + "ESG File Update Notification"); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(userAddress)); //msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(userAddress)); msg.setText(messageText); Transport.send(msg); success = true; } catch (MessagingException ex) { log.error("Problem Sending Email Notification: to " + userid + ": " + userAddress + " (" + subject + ")\n" + messageText + "\n", ex); } msg = null; //gc niceness return success; }
From source file:fsi_admin.JSmtpConn.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String ERROR = null, codErr = null; try {/*from w w w. java 2 s . co m*/ Properties parametros = new Properties(); Vector archivos = new Vector(); DiskFileUpload fu = new DiskFileUpload(); List items = fu.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) parametros.put(item.getFieldName(), item.getString()); else archivos.addElement(item); } if (parametros.getProperty("SERVER") == null || parametros.getProperty("DATABASE") == null || parametros.getProperty("USER") == null || parametros.getProperty("PASSWORD") == null || parametros.getProperty("BODY") == null || parametros.getProperty("MIMETYPE") == null || parametros.getProperty("SUBJECT") == null || parametros.getProperty("EMAIL") == null || parametros.getProperty("SOURCEMAIL") == null) { System.out.println("No recibi parametros de conexin antes del correo a enviar"); ERROR = "ERROR: El servidor no recibi todos los parametros de conexion (SERVER,DATABASE,USER,PASSWORD) antes del correo a enviar"; codErr = "3"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 3); } //Hasta aqui se han enviado todos los parametros ninguno nulo if (ERROR == null) { StringBuffer msj = new StringBuffer(), SMTPHOST = new StringBuffer(), SMTPPORT = new StringBuffer(), SMTPUSR = new StringBuffer(), SMTPPASS = new StringBuffer(); MutableBoolean COBRAR = new MutableBoolean(false); MutableDouble COSTO = new MutableDouble(0.0), SALDO = new MutableDouble(0.0); // Primero obtiene info del SMTP if (!obtenInfoSMTP(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("DATABASE"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), SMTPHOST, SMTPPORT, SMTPUSR, SMTPPASS, msj, COSTO, SALDO, COBRAR)) { System.out.println("El usuario y contrasea de servicio estan mal"); ERROR = msj.toString(); codErr = "2"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 2); } else { if (COBRAR.booleanValue() && SALDO.doubleValue() < COSTO.doubleValue()) { System.out.println("El servicio tiene un costo que no alcanza en el saldo"); ERROR = "El servicio SMTP tiene un costo que no alcanza en el saldo"; codErr = "2"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 2); } else { Properties props; props = System.getProperties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.port", Integer.parseInt(SMTPPORT.toString())); // Set properties indicating that we want to use STARTTLS to encrypt the connection. // The SMTP session will begin on an unencrypted connection, and then the client // will issue a STARTTLS command to upgrade to an encrypted connection. props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.starttls.required", "true"); // Create a Session object to represent a mail session with the specified properties. Session session = Session.getDefaultInstance(props); MimeMessage mmsg = new MimeMessage(session); BodyPart messagebodypart = new MimeBodyPart(); MimeMultipart multipart = new MimeMultipart(); if (!prepareMsg(parametros.getProperty("SOURCEMAIL"), parametros.getProperty("EMAIL"), parametros.getProperty("SUBJECT"), parametros.getProperty("MIMETYPE"), parametros.getProperty("BODY"), msj, props, session, mmsg, messagebodypart, multipart)) { System.out.println("No se permiti preparar el mensaje"); ERROR = msj.toString(); codErr = "3"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 3); } else { if (!adjuntarArchivo(msj, messagebodypart, multipart, archivos)) { System.out.println("No se permiti adjuntar archivos al mensaje"); ERROR = msj.toString(); codErr = "3"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 3); } else { if (!sendMsg(SMTPHOST.toString(), SMTPUSR.toString(), SMTPPASS.toString(), msj, session, mmsg, multipart)) { System.out.println("No se permiti enviar el mensaje"); ERROR = msj.toString(); codErr = "3"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 3); } else { ingresarRegistroExitoso(parametros.getProperty("SERVER"), parametros.getProperty("DATABASE"), parametros.getProperty("SUBJECT"), COSTO, SALDO, COBRAR); //Devuelve la respuesta al cliente Element Correo = new Element("Correo"); Correo.setAttribute("Subject", parametros.getProperty("SUBJECT")); Correo.setAttribute("MsjError", ""); Document Reporte = new Document(Correo); Format format = Format.getPrettyFormat(); format.setEncoding("utf-8"); format.setTextMode(TextMode.NORMALIZE); XMLOutputter xmlOutputter = new XMLOutputter(format); ByteArrayOutputStream out = new ByteArrayOutputStream(); xmlOutputter.output(Reporte, out); byte[] data = out.toByteArray(); ByteArrayInputStream istream = new ByteArrayInputStream(data); String destino = "Correo.xml"; JBajarArchivo fd = new JBajarArchivo(); fd.doDownload(response, getServletConfig().getServletContext(), istream, "text/xml", data.length, destino); } } } } } } } catch (Exception e) { e.printStackTrace(); ERROR = "ERROR DE EXCEPCION EN SERVIDOR PAC: " + e.getMessage(); } //Genera el archivo XML de error para ser devuelto al Servidor if (ERROR != null) { Element SIGN_ERROR = new Element("SIGN_ERROR"); SIGN_ERROR.setAttribute("CodError", codErr); SIGN_ERROR.setAttribute("MsjError", ERROR); Document Reporte = new Document(SIGN_ERROR); Format format = Format.getPrettyFormat(); format.setEncoding("utf-8"); format.setTextMode(TextMode.NORMALIZE); XMLOutputter xmlOutputter = new XMLOutputter(format); ByteArrayOutputStream out = new ByteArrayOutputStream(); xmlOutputter.output(Reporte, out); byte[] data = out.toByteArray(); ByteArrayInputStream istream = new ByteArrayInputStream(data); String destino = "SIGN_ERROR.xml"; JBajarArchivo fd = new JBajarArchivo(); fd.doDownload(response, getServletConfig().getServletContext(), istream, "text/xml", data.length, destino); } }
From source file:it.eng.spagobi.tools.scheduler.dispatcher.DistributionListDocumentDispatchChannel.java
public boolean dispatch(BIObject document, byte[] executionOutput) { String contentType;/* ww w . ja va2s . c o m*/ String fileExtension; String nameSuffix; JobExecutionContext jobExecutionContext; logger.debug("IN"); try { contentType = dispatchContext.getContentType(); fileExtension = dispatchContext.getFileExtension(); nameSuffix = dispatchContext.getNameSuffix(); jobExecutionContext = dispatchContext.getJobExecutionContext(); //Custom Trusted Store Certificate Options String trustedStorePath = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.file"); String trustedStorePassword = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.password"); 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); if ((smtphost == null) || smtphost.trim().equals("")) throw new Exception("Smtp host not configured"); String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from"); if ((from == null) || from.trim().equals("")) from = "spagobi.scheduler@eng.it"; int smptPort = 25; if ((smtpport == null) || smtpport.trim().equals("")) { throw new Exception("Smtp host not configured"); } else { smptPort = Integer.parseInt(smtpport); } String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user"); String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); /* if( (user==null) || user.trim().equals("")) throw new Exception("Smtp user not configured"); if( (pass==null) || pass.trim().equals("")) throw new Exception("Smtp password not configured"); */ String mailTos = ""; List dlIds = dispatchContext.getDlIds(); Iterator it = dlIds.iterator(); while (it.hasNext()) { Integer dlId = (Integer) it.next(); DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId); List emails = new ArrayList(); emails = dl.getEmails(); Iterator j = emails.iterator(); while (j.hasNext()) { Email e = (Email) j.next(); String email = e.getEmail(); String userTemp = e.getUserId(); IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp); if (ObjectsAccessVerifier.canSee(document, userProfile)) { if (j.hasNext()) { mailTos = mailTos + email + ","; } else { mailTos = mailTos + email; } } } } if ((mailTos == null) || mailTos.trim().equals("")) { throw new Exception("No recipient address found"); } String[] recipients = mailTos.split(","); //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.port", Integer.toString(smptPort)); Session session = null; if (StringUtilities.isEmpty(user) || StringUtilities.isEmpty(pass)) { props.put("mail.smtp.auth", "false"); session = Session.getInstance(props); logger.debug("Connecting to mail server without authentication"); } else { props.put("mail.smtp.auth", "true"); Authenticator auth = new SMTPAuthenticator(user, pass); //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.getInstance(props, auth); logger.debug("Connecting to mail server with authentication"); } // 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 IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder(); String subject = document.getName() + nameSuffix; msg.setSubject(subject); // create and fill the first message part //MimeBodyPart mbp1 = new MimeBodyPart(); //mbp1.setText(mailTxt); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message SchedulerDataSource sds = new SchedulerDataSource(executionOutput, contentType, document.getName() + 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); } if (jobExecutionContext.getNextFireTime() == null) { String triggername = jobExecutionContext.getTrigger().getName(); dlIds = dispatchContext.getDlIds(); it = dlIds.iterator(); while (it.hasNext()) { Integer dlId = (Integer) it.next(); DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId); DAOFactory.getDistributionListDAO().eraseDistributionListObjects(dl, (document.getId()).intValue(), triggername); } } } catch (Exception e) { logger.error("Error while sending schedule result mail", e); return false; } finally { logger.debug("OUT"); } return true; }