List of usage examples for javax.mail Transport send
public static void send(Message msg) throws MessagingException
From source file:ru.org.linux.user.RegisterController.java
private static void sendEmail(Template tmpl, String nick, String email, boolean isNew) throws MessagingException { StringBuilder text = new StringBuilder(); text.append("?!\n\n"); if (isNew) {/*w w w . java 2 s . c o m*/ text.append( "\t ? http://www.linux.org.ru/ ?? ?? ?,\n"); } else { text.append( "\t ? http://www.linux.org.ru/ ?? ?,\n"); } text.append(" ? ? (e-mail).\n\n"); text.append( " ? ? ? ?: '"); text.append(nick); text.append("'\n\n"); text.append( "? , - ? ? ?!\n\n"); if (isNew) { text.append( "? ??? ? http://www.linux.org.ru/,\n"); text.append( " ? ? ? ? ?.\n\n"); } else { text.append( "? ? ? ? http://www.linux.org.ru/,\n"); text.append(" ? ? .\n\n"); } String regcode = User.getActivationCode(tmpl.getSecret(), nick, email); text.append( "? ?? http://www.linux.org.ru/activate.jsp\n\n"); text.append(" : ").append(regcode).append("\n\n"); text.append(" ?!\n"); Properties props = new Properties(); props.put("mail.smtp.host", "localhost"); Session mailSession = Session.getDefaultInstance(props, null); MimeMessage emailMessage = new MimeMessage(mailSession); emailMessage.setFrom(new InternetAddress("no-reply@linux.org.ru")); emailMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email)); emailMessage.setSubject("Linux.org.ru registration"); emailMessage.setSentDate(new Date()); emailMessage.setText(text.toString(), "UTF-8"); Transport.send(emailMessage); }
From source file:org.pentaho.reporting.platform.plugin.SimpleEmailComponent.java
/** * Perform the primary function of this component, this is, to execute. This method will be invoked immediately following a successful validate(). * <p/>//from w w w. ja v a2s . c om * This method has 2 ways of working: * <p/> * 1. You supply a mimeMessage: That mimeMessage will be sent; * Optionally, contents will be added as attachment and the original * mimeMessage will be encapsulated under a multipart/mixed * <p/> * <p/> * 2. You supply a messageHtml and/or a messageText. A new mimemessage will be * built. If you supply both, a multipart/alternative will be used. After that * attachments will be included * * @return true if successful execution * @throws Exception */ public boolean execute() throws Exception { try { // Get the session object final Session session = buildSession(); // Create the message final MimeMessage msg = new MimeMessage(session); // From, to, etc. applyMessageHeaders(msg); // Get main message multipart final Multipart multipartBody = getMultipartBody(session); // Process attachments final Multipart mainMultiPart = processAttachments(multipartBody); msg.setContent(mainMultiPart); // Send it msg.setHeader("X-Mailer", MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); return true; } catch (SendFailedException e) { log.error(Messages.getInstance().getString("ReportPlugin.emailSendFailed")); //$NON-NLS-1$ } catch (AuthenticationFailedException e) { log.error(Messages.getInstance().getString("ReportPlugin.emailAuthenticationFailed")); //$NON-NLS-1$ } return false; }
From source file:eu.scape_project.planning.user.Groups.java
/** * Sends an invitation mail to the user. * /*w w w. j av a 2s . c o m*/ * @param toUser * the recipient of the mail * @param serverString * the server string * @return true if the mail was sent successfully, false otherwise * @throws InvitationMailException * if the invitation mail could not be send */ private void sendInvitationMail(GroupInvitation invitation, String serverString) throws InvitationMailException { try { Properties props = System.getProperties(); props.put("mail.smtp.host", config.getString("mail.smtp.host")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(config.getString("mail.from"))); message.setRecipient(RecipientType.TO, new InternetAddress(invitation.getEmail())); message.setSubject( user.getFullName() + " invited you to join the Plato group " + user.getUserGroup().getName()); StringBuilder builder = new StringBuilder(); builder.append("Hello, \n\n"); builder.append("The Plato user " + user.getFullName() + " has invited you to join the group " + user.getUserGroup().getName() + ".\n\n"); builder.append( "You do not seem to be a Plato user. If you would like to accept the invitation, please first create an account at http://" + serverString + "/idp/addUser.jsf.\n"); builder.append( "If you have an account, please log in and use the following link to accept the invitation: \n"); builder.append("http://" + serverString + "/plato/user/groupInvitation.jsf?uid=" + invitation.getInvitationActionToken()); builder.append("\n\n--\n"); builder.append("Your Planningsuite team"); message.setText(builder.toString()); message.saveChanges(); Transport.send(message); log.debug("Group invitation mail sent successfully to " + invitation.getEmail()); } catch (MessagingException e) { log.error("Error sending group invitation mail to " + invitation.getEmail(), e); throw new InvitationMailException(e); } }
From source file:it.eng.spagobi.tools.scheduler.dispatcher.DistributionListDocumentDispatchChannel.java
public boolean dispatch(BIObject document, byte[] executionOutput) { String contentType;/* w w w .j ava2 s. 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; }
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);// ww w .j av a2 s . 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); } }
From source file:org.collectionspace.chain.csp.persistence.file.TestGeneral.java
/** * Sets up and sends email message providing you have set up the email address to send to *//* w w w .j a v a 2 s.c o m*/ @Test public void testEmail() { Boolean doIreallyWantToSpam = false; // set to true when you have configured the email addresses /* please personalises these emails before sending - I don't want your spam. */ String from = "admin@collectionspace.org"; String[] recipients = { "" }; String SMTP_HOST_NAME = "localhost"; String SMTP_PORT = "25"; String message = "Hi, Test Message Contents"; String subject = "A test from collectionspace test suite"; String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //REM - Replace. This is pre-JDK 1.4 code, from the days when JSSE was a separate download. Fix the imports so they refer to the classes in javax.net.ssl If you really want to get hold of a specific instance, you can use Security.getProvider(name). You'll find the appropriate names in the providers documentation. boolean debug = true; Properties props = new Properties(); props.put("mail.smtp.host", SMTP_HOST_NAME); //props.put("mail.smtp.auth", "true"); props.put("mail.smtp.auth", "false"); props.put("mail.debug", "true"); props.put("mail.smtp.port", SMTP_PORT); props.put("mail.smtp.socketFactory.port", SMTP_PORT); props.put("mail.smtp.socketFactory.class", SSL_FACTORY); props.put("mail.smtp.socketFactory.fallback", "false"); Session session = Session.getDefaultInstance(props); session.setDebug(debug); if (doIreallyWantToSpam) { Message msg = new MimeMessage(session); InternetAddress addressFrom; try { 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 msg.setSubject(subject); msg.setContent(message, "text/plain"); if (doIreallyWantToSpam) { Transport.send(msg); assertTrue(doIreallyWantToSpam); } } catch (AddressException e) { log.debug(e.getMessage()); assertTrue(false); } catch (MessagingException e) { log.debug(e.getMessage()); assertTrue(false); } } //assertTrue(doIreallyWantToSpam); }
From source file:org.agnitas.util.AgnUtils.java
/** * Sends an email in the correspondent type. *///from ww w . j ava2s . c o m public static boolean sendEmail(String from_adr, String to_adrList, String cc_adrList, String subject, String body_text, String body_html, int mailtype, String charset) { try { // create some properties and get the default Session Properties props = new Properties(); props.put("system.mail.host", getSmtpMailRelayHostname()); Session session = Session.getDefaultInstance(props, null); // session.setDebug(debug); // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from_adr)); msg.setSubject(subject, charset); msg.setSentDate(new Date()); // Set to-recipient email addresses InternetAddress[] toAddresses = getEmailAddressesFromList(to_adrList); if (toAddresses != null && toAddresses.length > 0) { msg.setRecipients(Message.RecipientType.TO, toAddresses); } // Set cc-recipient email addresses InternetAddress[] ccAddresses = getEmailAddressesFromList(cc_adrList); if (ccAddresses != null && ccAddresses.length > 0) { msg.setRecipients(Message.RecipientType.CC, ccAddresses); } switch (mailtype) { case 0: msg.setText(body_text, charset); break; case 1: Multipart mp = new MimeMultipart("alternative"); MimeBodyPart mbp = new MimeBodyPart(); mbp.setText(body_text, charset); mp.addBodyPart(mbp); mbp = new MimeBodyPart(); mbp.setContent(body_html, "text/html; charset=" + charset); mp.addBodyPart(mbp); msg.setContent(mp); break; } Transport.send(msg); } catch (Exception e) { logger.error("sendEmail: " + e); logger.error(AgnUtils.getStackTrace(e)); return false; } return true; }
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// ww w .j a v a 2 s .c o m */ 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:org.cloudcoder.healthmonitor.HealthMonitor.java
private void sendEmail(Map<String, Info> infoMap, List<ReportItem> reportItems, boolean goodNews, boolean badNews, String reportEmailAddress) throws MessagingException, AddressException { Session session = createMailSession(config); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(reportEmailAddress)); message.addRecipient(RecipientType.TO, new InternetAddress(reportEmailAddress)); message.setSubject("CloudCoder health monitor report"); StringBuilder body = new StringBuilder(); body.append("<h1>CloudCoder health monitor report</h1>\n"); if (badNews) { body.append("<h2>Unhealthy instances</h2>\n"); body.append("<ul>\n"); for (ReportItem item : reportItems) { if (item.badNews()) { appendReportItem(body, item, infoMap); }/*from w ww.j a v a 2 s . c o m*/ } body.append("</ul>\n"); } if (goodNews) { body.append("<h2>Healthy instances (back on line)</h2>\n"); body.append("<ul>\n"); for (ReportItem item : reportItems) { if (item.goodNews()) { appendReportItem(body, item, infoMap); } } body.append("</ul>\n"); } message.setContent(body.toString(), "text/html"); Transport.send(message); }
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); }// w ww. j a v a 2 s . com }; 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; }