List of usage examples for javax.mail.internet MimeMessage setFrom
public void setFrom(String address) throws MessagingException
From source file:jp.co.acroquest.endosnipe.collector.notification.smtp.SMTPSender.java
/** * ??/*w ww . j a v a 2s . c o m*/ * * @param config javelin.properties??? * @param entry ?? * @return ??? * @throws MessagingException ?????? */ protected MimeMessage createMailMessage(final DataCollectorConfig config, final AlarmEntry entry) throws MessagingException { // JavaMail??? Properties props = System.getProperties(); String smtpServer = this.config_.getSmtpServer(); if (smtpServer == null || smtpServer.length() == 0) { LOGGER.log(LogMessageCodes.SMTP_SERVER_NOT_SPECIFIED); String detailMessageKey = "collector.notification.smtp.SMTPSender.SMTPNotSpecified"; String messageDetail = CommunicatorMessages.getMessage(detailMessageKey); throw new MessagingException(messageDetail); } props.setProperty(SMTP_HOST_KEY, smtpServer); int smtpPort = config.getSmtpPort(); props.setProperty(SMTP_PORT_KEY, String.valueOf(smtpPort)); // ??????? Session session = null; if (authenticator_ == null) { // ????? session = Session.getDefaultInstance(props); } else { // ??? props.setProperty(SMTP_AUTH_KEY, "true"); session = Session.getDefaultInstance(props, authenticator_); } // MIME?? MimeMessage message = new MimeMessage(session); // ?? // : Date date = new Date(); String encoding = this.config_.getSmtpEncoding(); message.setHeader("X-Mailer", X_MAILER); message.setHeader("Content-Type", "text/plain; charset=\"" + encoding + "\""); message.setSentDate(date); // :from String from = this.config_.getSmtpFrom(); InternetAddress fromAddr = new InternetAddress(from); message.setFrom(fromAddr); // :to String[] recipients = this.config_.getSmtpTo().split(","); for (String toStr : recipients) { InternetAddress toAddr = new InternetAddress(toStr); message.addRecipient(Message.RecipientType.TO, toAddr); } // :body, subject String subject; String body; subject = createSubject(entry, date); try { body = createBody(entry, date); } catch (IOException ex) { LOGGER.log(LogMessageCodes.FAIL_READ_MAIL_TEMPLATE, ""); body = createDefaultBody(entry, date); } message.setSubject(subject, encoding); message.setText(body, encoding); return message; }
From source file:com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController.java
public String[] notifyExternals(InfoLetterPublicationPdC ilp, String server, List<String> emails) { // Retrieve SMTP server information String host = getSmtpHost();//from w ww.j a v a 2 s. com boolean isSmtpAuthentication = isSmtpAuthentication(); int smtpPort = getSmtpPort(); String smtpUser = getSmtpUser(); String smtpPwd = getSmtpPwd(); boolean isSmtpDebug = isSmtpDebug(); List<String> emailErrors = new ArrayList<String>(); if (emails.size() > 0) { // Corps et sujet du message String subject = getString("infoLetter.emailSubject") + ilp.getName(); // Email du publieur String from = getUserDetail().geteMail(); // create some properties and get the default Session Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.auth", String.valueOf(isSmtpAuthentication)); Session session = Session.getInstance(props, null); session.setDebug(isSmtpDebug); // print on the console all SMTP messages. SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "subject = " + subject); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "from = " + from); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "host= " + host); try { // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setSubject(subject, CharEncoding.UTF_8); ForeignPK foreignKey = new ForeignPK(ilp.getPK().getId(), getComponentId()); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); List<SimpleDocument> contents = AttachmentServiceFactory.getAttachmentService() .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.wysiwyg, I18NHelper.defaultLanguage); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for (SimpleDocument content : contents) { AttachmentServiceFactory.getAttachmentService().getBinaryContent(buffer, content.getPk(), content.getLanguage()); } mbp1.setDataHandler( new DataHandler(new ByteArrayDataSource( replaceFileServerWithLocal( IOUtils.toString(buffer.toByteArray(), CharEncoding.UTF_8), server), MimeTypes.HTML_MIME_TYPE))); IOUtils.closeQuietly(buffer); // Fichiers joints WAPrimaryKey publiPK = ilp.getPK(); publiPK.setComponentName(getComponentId()); publiPK.setSpace(getSpaceId()); // create the Multipart and its parts to it String mimeMultipart = getSettings().getString("SMTPMimeMultipart", "related"); Multipart mp = new MimeMultipart(mimeMultipart); mp.addBodyPart(mbp1); // Images jointes List<SimpleDocument> fichiers = AttachmentServiceFactory.getAttachmentService() .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.image, null); for (SimpleDocument attachment : fichiers) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(attachment.getAttachmentPath()); mbp2.setDataHandler(new DataHandler(fds)); // For Displaying images in the mail mbp2.setFileName(attachment.getFilename()); mbp2.setHeader("Content-ID", attachment.getFilename()); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID()); // create the Multipart and its parts to it mp.addBodyPart(mbp2); } // Fichiers joints fichiers = AttachmentServiceFactory.getAttachmentService() .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.attachment, null); if (!fichiers.isEmpty()) { for (SimpleDocument attachment : fichiers) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(attachment.getAttachmentPath()); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(attachment.getFilename()); // For Displaying images in the mail mbp2.setHeader("Content-ID", attachment.getFilename()); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID()); // create the Multipart and its parts to it mp.addBodyPart(mbp2); } } // add the Multipart to the message msg.setContent(mp); // set the Date: header msg.setSentDate(new Date()); // create a Transport connection (TCP) Transport transport = session.getTransport("smtp"); InternetAddress[] address = new InternetAddress[1]; for (String email : emails) { try { address[0] = new InternetAddress(email); msg.setRecipients(Message.RecipientType.TO, address); // add Transport Listener to the transport connection. if (isSmtpAuthentication) { SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "host = " + host + " m_Port=" + smtpPort + " m_User=" + smtpUser); transport.connect(host, smtpPort, smtpUser, smtpPwd); msg.saveChanges(); } else { transport.connect(); } transport.sendMessage(msg, address); } catch (Exception ex) { SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "Email = " + email, new InfoLetterException( "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController", SilverpeasRuntimeException.ERROR, ex.getMessage(), ex)); emailErrors.add(email); } finally { if (transport != null) { try { transport.close(); } catch (Exception e) { SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.EX_IGNORED", "ClosingTransport", e); } } } } } catch (Exception e) { throw new InfoLetterException( "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController", SilverpeasRuntimeException.ERROR, e.getMessage(), e); } } return emailErrors.toArray(new String[emailErrors.size()]); }
From source file:bean.RedSocial.java
/** * //from w w w.j a va 2 s . c om * @param _username * @param _email * @param _password */ @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = transactionalBusinessException.ComentariosViaException.class) public void solicitarAcceso(String _username, String _email, String _password) { if (daoUsuario.obtenerUsuario(_username) != null) { throw new exceptionsBusiness.UsernameNoDisponible(); } String hash = BCrypt.hashpw(_password, BCrypt.gensalt()); Token token = new Token(_username, _email, hash); daoToken.guardarToken(token); //enviar token de acceso a la direccion email String correoEnvia = "skala2climbing@gmail.com"; String claveCorreo = "vNspLa5H"; // La configuracin para enviar correo Properties properties = new Properties(); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.auth", "true"); properties.put("mail.user", correoEnvia); properties.put("mail.password", claveCorreo); // Obtener la sesion Session session = Session.getInstance(properties, null); try { // Crear el cuerpo del mensaje MimeMessage mimeMessage = new MimeMessage(session); // Agregar quien enva el correo mimeMessage.setFrom(new InternetAddress(correoEnvia, "Skala2Climbing")); // Los destinatarios InternetAddress[] internetAddresses = { new InternetAddress(token.getEmail()) }; // Agregar los destinatarios al mensaje mimeMessage.setRecipients(Message.RecipientType.TO, internetAddresses); // Agregar el asunto al correo mimeMessage.setSubject("Confirmacin de registro"); // Creo la parte del mensaje MimeBodyPart mimeBodyPart = new MimeBodyPart(); String ip = "90.165.24.228"; mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: http://" + ip + ":8383/redsocialcolaborativaclientangularjs/confirmacion.html?" + "token=" + token.getToken()); //mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: "+"Enlace an no disponible"); // Crear el multipart para agregar la parte del mensaje anterior Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); // Agregar el multipart al cuerpo del mensaje mimeMessage.setContent(multipart); // Enviar el mensaje Transport transport = session.getTransport("smtp"); transport.connect(correoEnvia, claveCorreo); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); transport.close(); } catch (UnsupportedEncodingException | MessagingException ex) { throw new ErrorEnvioEmail(); } }
From source file:mitm.application.djigzo.james.mailets.SMIMESignTest.java
@Test public void testInvalidFrom() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); mailetConfig.setInitParameter("catchRuntimeExceptions", "false"); SMIMESign mailet = new SMIMESign(); mailet.init(mailetConfig);/* ww w .j av a2 s .c o m*/ MockMail mail = new MockMail(); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-message.eml")); message.setFrom(new InternetAddress("xxx")); message.saveChanges(); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("m.brinkers@pobox.com")); mail.setRecipients(recipients); mail.setSender(null); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); SMIMEInspector inspector = new SMIMEInspectorImpl(mail.getMessage(), null, "BC"); assertEquals(SMIMEType.NONE, inspector.getSMIMEType()); }
From source file:mitm.application.djigzo.james.mailets.SMIMEEncryptTest.java
@Test public void testProtectedHeadersStatic() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SMIMEEncrypt mailet = new SMIMEEncrypt(); mailetConfig.setInitParameter("retainMessageID", "false"); mailetConfig.setInitParameter("protectedHeader", "from, message-id"); mailet.init(mailetConfig);/*from w ww .j av a 2 s. co m*/ Mail mail = new MockMail(); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-message-with-id.eml")); assertEquals("<123456>", message.getMessageID()); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("test@example.com")); mail.setRecipients(recipients); DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail); mailAttributes.setCertificates(certificates); mailet.service(mail); MimeMessage encrypted = mail.getMessage(); /* * Change from to see whether it was protected */ encrypted.setFrom(new InternetAddress("changed@changed.example.com")); MailUtils.validateMessage(encrypted); assertFalse("<123456>".equals(encrypted.getMessageID())); assertEquals(SMIMEHeader.ENCRYPTED_CONTENT_TYPE, encrypted.getContentType()); KeyStoreKeyProvider keyStore = new KeyStoreKeyProvider( loadKeyStore(new File("test/resources/testdata/keys/testCertificates.p12"), "test"), "test"); SMIMEInspector inspector = new SMIMEInspectorImpl(encrypted, keyStore, "BC"); assertEquals(SMIMEType.ENCRYPTED, inspector.getSMIMEType()); /* * now decrypt and check whether message-id and from was protected */ MimeMessage decrypted = inspector.getContentAsMimeMessage(); inspector = new SMIMEInspectorImpl(decrypted, keyStore, "BC"); assertEquals(SMIMEType.NONE, inspector.getSMIMEType()); assertTrue("<123456>".equals(decrypted.getMessageID())); assertEquals("test@example.com", StringUtils.join(decrypted.getFrom())); }
From source file:mitm.application.djigzo.james.mailets.SMIMEEncryptTest.java
@Test public void testProtectedHeadersMailAttributes() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SMIMEEncrypt mailet = new SMIMEEncrypt(); mailetConfig.setInitParameter("retainMessageID", "false"); mailet.init(mailetConfig);/*from w w w .ja va2s. co m*/ Mail mail = new MockMail(); DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail); /* * set protected headers in the mail attributes */ mailAttributes.setProtectedHeaders(new String[] { "from", "message-id" }); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-message-with-id.eml")); assertEquals("<123456>", message.getMessageID()); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("test@example.com")); mail.setRecipients(recipients); mailAttributes.setCertificates(certificates); mailet.service(mail); MimeMessage encrypted = mail.getMessage(); /* * Change from to see whether it was protected */ encrypted.setFrom(new InternetAddress("changed@changed.example.com")); MailUtils.validateMessage(encrypted); assertFalse("<123456>".equals(encrypted.getMessageID())); assertEquals(SMIMEHeader.ENCRYPTED_CONTENT_TYPE, encrypted.getContentType()); KeyStoreKeyProvider keyStore = new KeyStoreKeyProvider( loadKeyStore(new File("test/resources/testdata/keys/testCertificates.p12"), "test"), "test"); SMIMEInspector inspector = new SMIMEInspectorImpl(encrypted, keyStore, "BC"); assertEquals(SMIMEType.ENCRYPTED, inspector.getSMIMEType()); /* * now decrypt and check whether message-id and from was protected */ MimeMessage decrypted = inspector.getContentAsMimeMessage(); inspector = new SMIMEInspectorImpl(decrypted, keyStore, "BC"); assertEquals(SMIMEType.NONE, inspector.getSMIMEType()); assertTrue("<123456>".equals(decrypted.getMessageID())); assertEquals("test@example.com", StringUtils.join(decrypted.getFrom())); }
From source file:cz.incad.vdkcommon.solr.Indexer.java
private void sendDemandMail(SolrDocument resultDoc, String id) { try {/*from ww w . ja v a2 s .c o m*/ String title = (String) resultDoc.getFieldValues("title").toArray()[0]; String pop = (String) resultDoc.getFieldValue("poptavka_ext"); JSONObject j = new JSONObject(pop); String from = opts.getString("admin.email"); Knihovna kn = new Knihovna(j.getString("knihovna")); String to = kn.getEmail(); String zaznam = j.optString("zaznam"); String code = j.optString("code"); String exemplar = j.optString("exemplar"); try { Properties properties = System.getProperties(); Session session = Session.getDefaultInstance(properties); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(opts.getString("admin.email.demand.subject")); String link = opts.getString("app.url") + "/original?id=" + id; String body = opts.getString("admin.email.demand.body").replace("${demand.title}", title) .replace("${demand.url}", link); message.setText(body); Transport.send(message); LOGGER.fine("Sent message successfully...."); } catch (MessagingException ex) { LOGGER.log(Level.SEVERE, "Error sending email to: {0}, from {1} ", new Object[] { to, from }); LOGGER.log(Level.SEVERE, null, ex); } } catch (NamingException | SQLException ex) { LOGGER.log(Level.SEVERE, null, ex); } }
From source file:trendplot.TrendPlot.java
private void testEmail() { Properties fMailServerConfig; fMailServerConfig = new Properties(); fMailServerConfig.setProperty("mail.host", "ldas-cit.ligo.caltech.edu"); fMailServerConfig.setProperty("mail.smtp.host", "ldas-cit.ligo.caltech.edu"); Session session = Session.getDefaultInstance(fMailServerConfig, null); MimeMessage message = new MimeMessage(session); try {// w w w . j a v a2 s .co m //the "from" address may be set in code, or set in the //config file under "mail.from" ; here, the latter style is used message.setFrom(new InternetAddress("areeda@ligo.caltech.edu")); String email = "joe@areeda.com"; message.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); String msg = "<h3>this is a test</h3>"; message.setSubject("Test email"); message.setText(msg, "utf-8", "html"); Transport.send(message); System.out.format("Email sent to %1$s\n", email); } catch (MessagingException ex) { System.err.format("Exception: %1$s: %2$s", ex.getClass().getSimpleName(), ex.getLocalizedMessage()); } }
From source file:com.meltmedia.cadmium.email.TestingMessageTransformer.java
public MimeMessage transform(MimeMessage message) throws MessagingException { MimeBodyPart sentToBodyPart = newSentToBodyPart(message); MimeBodyPart originalBodyPart = newOriginalBodyPart(message); // create a new multipart content for this message. MimeMultipart multipart = new MimeMultipart(EmailUtil.SUBTYPE_MIXED); // add the parts to the body. multipart.addBodyPart(originalBodyPart); multipart.addBodyPart(sentToBodyPart); // get the new values for all of the headers. InternetAddress newFromAddress = newFromAddress(message); InternetAddress[] newToAddresses = newToAddresses(message); InternetAddress[] newCcAddresses = newCcAddresses(message); InternetAddress[] newBccAddresses = newBccAddresses(message); String newSubject = newSubject(message); // update the message. message.setFrom(newFromAddress); message.setRecipients(Message.RecipientType.TO, newToAddresses); message.setRecipients(Message.RecipientType.CC, newCcAddresses); message.setRecipients(Message.RecipientType.BCC, newBccAddresses); message.setSubject(newSubject);//from w ww . j a v a 2 s . c o m message.setContent(multipart); // save the message. message.saveChanges(); if (getLogProperty()) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); message.writeTo(out); log.info("Email Message Sent:\n{}", out.toString()); } catch (IOException ioe) { throw new MessagingException("Exception thrown while writing message to log.", ioe); } } if (!getSendProperty()) { message = null; } // return the message. return message; }
From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java
/** * Send an mail containing the error message back to the * user which sent the given message.//from w w w . j a v a 2 s. c o m * * @param m The message which produced an error while handling it. * @param error The error string. */ private void sendErrorMessage(Message m, String error) throws Exception { /* get the SMTP mail server */ SMTPMailServer smtpMailServer = MailFactory.getServerManager().getDefaultSMTPMailServer(); if (smtpMailServer == null) { log.warn("Failed to send error message as no SMTP server is configured"); return; } /* get system properties */ Properties props = System.getProperties(); /* Setup mail server */ props.put("mail.smtp.host", smtpMailServer.getHostname()); /* get a session */ Session session = Session.getDefaultInstance(props, null); /* create the message */ MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(smtpMailServer.getDefaultFrom())); String senderEmail = getEmailAddressFromMessage(m); if (senderEmail == "") { throw new Exception("Unknown sender of email."); } message.addRecipient(Message.RecipientType.TO, new InternetAddress(senderEmail)); message.setSubject("[mail2news] Error while handling message (" + m.getSubject() + ")"); message.setText("An error occurred while handling your message:\n\n " + error + "\n\nPlease contact the administrator to solve the problem.\n"); /* send the message */ Transport tr = session.getTransport("smtp"); if (StringUtils.isBlank(smtpMailServer.getSmtpPort())) { tr.connect(smtpMailServer.getHostname(), smtpMailServer.getUsername(), smtpMailServer.getPassword()); } else { int smtpPort = Integer.parseInt(smtpMailServer.getSmtpPort()); tr.connect(smtpMailServer.getHostname(), smtpPort, smtpMailServer.getUsername(), smtpMailServer.getPassword()); } message.saveChanges(); tr.sendMessage(message, message.getAllRecipients()); tr.close(); }