List of usage examples for javax.mail.internet MimeMessage setRecipient
public void setRecipient(RecipientType type, Address address) throws MessagingException
From source file:com.sangupta.jerry.email.service.impl.SmtpEmailServiceImpl.java
/** * @see com.sangupta.jerry.email.service.EmailService#sendEmail(com.sangupta.jerry.email.domain.Email) *//*from ww w . ja v a2s. c om*/ @Override public boolean sendEmail(final Email email) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { if (AssertUtils.isNotEmpty(email.getTo())) { for (EmailAddress address : email.getTo()) { mimeMessage.setRecipient(RecipientType.TO, address.getInternetAddress()); } } if (AssertUtils.isNotEmpty(email.getCc())) { for (EmailAddress address : email.getCc()) { mimeMessage.setRecipient(RecipientType.CC, address.getInternetAddress()); } } if (AssertUtils.isNotEmpty(email.getBcc())) { for (EmailAddress address : email.getBcc()) { mimeMessage.setRecipient(RecipientType.BCC, address.getInternetAddress()); } } if (AssertUtils.isNotEmpty(email.getReplyTo())) { Address[] replyTo = new Address[email.getReplyTo().size()]; int counter = 0; for (EmailAddress address : email.getReplyTo()) { replyTo[counter++] = address.getInternetAddress(); } mimeMessage.setReplyTo(replyTo); } mimeMessage.setFrom(email.getFrom().getInternetAddress()); mimeMessage.setSubject(email.getSubject()); mimeMessage.setContent(email.getText(), "text/html; charset=utf-8"); } }; try { this.mailSender.send(preparator); return true; } catch (MailException e) { LOGGER.error("Unable to send email", e); } return false; }
From source file:eu.planets_project.pp.plato.action.session.ExceptionAction.java
@RaiseEvent("exceptionHandled") public String sendMail() { try {/* www. ja v a2s. com*/ log.debug(body); Properties props = System.getProperties(); Properties mailProps = new Properties(); mailProps.load(ExceptionAction.class.getResourceAsStream("/mail.properties")); props.put("mail.smtp.host", mailProps.getProperty("SMTPSERVER")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(mailProps.getProperty("FROM"))); message.setRecipient(RecipientType.TO, new InternetAddress(mailProps.getProperty("TO"))); String exceptionType = "Unknown"; String exceptionMessage = ""; String stackTrace = ""; String host = ((HttpServletRequest) facesContext.getExternalContext().getRequest()).getLocalName(); if (lastHandledException != null) { exceptionType = lastHandledException.getClass().getCanonicalName(); exceptionMessage = lastHandledException.getMessage(); StringWriter writer = new StringWriter(); lastHandledException.printStackTrace(new PrintWriter(writer)); stackTrace = writer.toString(); } message.setSubject("[PlatoError] " + exceptionType + " at " + host); StringBuilder builder = new StringBuilder(); builder.append("Date: " + format.format(new Date()) + "\n"); builder.append("User: " + ((user == null) ? "Unknown" : user.getUsername()) + "\n"); builder.append("ExceptionType: " + exceptionType + "\n"); builder.append("ExceptionMessage: " + exceptionMessage + "\n\n"); builder.append("UserMail:" + separatorLine + this.userEmail + separatorLine + "\n"); builder.append("User Description:" + separatorLine + this.body + separatorLine + "\n"); builder.append(stackTrace); message.setText(builder.toString()); message.saveChanges(); Transport.send(message); this.lastHandledException = null; facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Bugreport sent.", "Thank you for your feedback. We will try to analyse and resolve the issue as soon as possible.")); } catch (Exception e) { log.debug(e.getMessage(), e); facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Bugreport couldn't be sent", "Because of an enternal error your bug report couldn't be sent. We apologise for this and hope you are willing to inform us about this so we can fix the problem. " + "Please send an email to plato@ifs.tuwien.ac.at with a " + "description of what you have been doing at the time of the error." + "Thank you very much!")); return null; } return "home"; }
From source file:net.duckling.ddl.service.mail.impl.MailServiceImpl.java
public void sendMail(Mail mail) { LOG.debug("sendEmail() to: " + mail.getRecipient()); try {//from ww w. j a v a 2s . c om Session session = Session.getInstance(m_bag.m_mailProperties, m_bag.m_authenticator); session.setDebug(false); MimeMessage msg = new MimeMessage(session); msg.setFrom(m_bag.m_fromAddress); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getRecipient())); msg.setSubject(mail.getSubject()); msg.setSentDate(new Date()); Multipart mp = new MimeMultipart(); MimeBodyPart txtmbp = new MimeBodyPart(); txtmbp.setContent(mail.getMessage(), EMAIL_CONTENT_TYPE); mp.addBodyPart(txtmbp); List<String> attachments = mail.getAttachments(); for (Iterator<String> it = attachments.iterator(); it.hasNext();) { MimeBodyPart mbp = new MimeBodyPart(); String filename = it.next(); FileDataSource fds = new FileDataSource(filename); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(MimeUtility.encodeText(fds.getName())); mp.addBodyPart(mbp); } msg.setContent(mp); if ((m_bag.m_fromAddress != null) && (m_bag.m_fromAddress.getAddress() != null) && (m_bag.m_fromAddress.getAddress().indexOf("@") != -1)) { cheat(msg, m_bag.m_fromAddress.getAddress().substring(m_bag.m_fromAddress.getAddress().indexOf("@"))); } Transport.send(msg); LOG.info("Successfully send the mail to " + mail.getRecipient()); } catch (Throwable e) { LOG.error("Exception occured while trying to send notification to: " + mail.getRecipient(), e); LOG.debug("Details:", e); } }
From source file:com.haulmont.cuba.core.app.EmailSender.java
protected void assignRecipient(SendingMessage sendingMessage, MimeMessage message) throws MessagingException { InternetAddress internetAddress = new InternetAddress(sendingMessage.getAddress().trim()); message.setRecipient(Message.RecipientType.TO, internetAddress); }
From source file:net.naijatek.myalumni.util.mail.FreeMarkerTemplateMailerImpl.java
public void mail(final String email, final Map map, final String bodyTemplatePrefix, final String subjectTemplatePrefix) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws MessagingException, IOException { mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(email)); ///*www. ja va 2 s . com*/ // Get the subject // //BodyPart subjectPart = new MimeBodyPart(); Template subjectTextTemplate = configuration.getTemplate(subjectTemplatePrefix); final StringWriter subjectTextWriter = new StringWriter(); try { subjectTextTemplate.process(map, subjectTextWriter); } catch (TemplateException e) { throw new MailPreparationException("Can't generate Subject Text", e); } mimeMessage.setSubject(subjectTextWriter.toString()); // // Create a "text" Multipart message // Template bodyTextTemplate = configuration.getTemplate(bodyTemplatePrefix); final StringWriter bodyTextWriter = new StringWriter(); try { bodyTextTemplate.process(map, bodyTextWriter); } catch (TemplateException e) { throw new MailPreparationException("Can't generate Body Text", e); } mimeMessage.setText(bodyTextWriter.toString()); /* // @TODO - This part handles sending an attachement textPart.setDataHandler(new DataHandler(new DataSource() { public InputStream getInputStream() throws IOException { return new StringBufferInputStream(bodyTextWriter.toString()); } public OutputStream getOutputStream() throws IOException { throw new IOException("Read-only data"); } public String getContentType() { return "text/plain"; } public String getName() { return "main"; } })); mp.addBodyPart(textPart);*/ /* // Create a "HTML" Multipart message Multipart htmlContent = new MimeMultipart("related"); BodyPart htmlPage = new MimeBodyPart(); Template htmlTemplate = configuration.getTemplate(templatePrefix + "-html.ftl"); final StringWriter htmlWriter = new StringWriter(); try { htmlTemplate.process(map, htmlWriter); } catch (TemplateException e) { throw new MailPreparationException("Can't generate HTML subscription mail", e); } htmlPage.setDataHandler(new DataHandler(new DataSource() { public InputStream getInputStream() throws IOException { return new StringBufferInputStream(htmlWriter.toString()); } public OutputStream getOutputStream() throws IOException { throw new IOException("Read-only data"); } public String getContentType() { return "text/html"; } public String getName() { return "main"; } })); htmlContent.addBodyPart(htmlPage); BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlContent); mp.addBodyPart(htmlPart); mimeMessage.setContent(mp);*/ } }; mailSender.send(preparator); }
From source file:com.srotya.tau.nucleus.qa.QAAlertRules.java
@Test public void testASMTPServerAvailability() throws UnknownHostException, IOException, MessagingException { MimeMessage msg = new MimeMessage(Session.getDefaultInstance(new Properties())); msg.setFrom(new InternetAddress("alert@srotya.com")); msg.setRecipient(RecipientType.TO, new InternetAddress("alert@srotya.com")); msg.setSubject("test mail"); msg.setContent("Hello", "text/html"); Transport.send(msg);//from w ww .j a v a 2 s . c o m MailService ms = new MailService(); ms.init(new HashMap<>()); Alert alert = new Alert(); alert.setBody("test"); alert.setId((short) 0); alert.setMedia("test"); alert.setSubject("test"); alert.setTarget("alert@srotya.com"); ms.sendMail(alert); assertEquals(2, AllQATests.getSmtpServer().getReceivedEmailSize()); System.err.println("Mail sent"); }
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.jav a 2s. 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:mitm.application.djigzo.ca.PFXMailBuilder.java
public MimeMessage createMessage() throws TemplateBuilderException { try {/*from w w w. jav a 2 s .c o m*/ checkState(); SimpleHash root = new SimpleHash(); root.put("from", from); root.put("recipient", recipient); root.put("recipientLocal", EmailAddressUtils.getLocalPart(recipient)); root.put("boundary", createBoundary()); if (properties != null) { root.putAll(properties); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); templateBuilder.buildTemplate(template, root, bos); MimeMessage templatedMessage = MailUtils.byteArrayToMessage(bos.toByteArray()); templatedMessage.setFrom(from); if (recipient != null) { templatedMessage.setRecipient(RecipientType.TO, recipient); } replacePFX(templatedMessage); /* * Make sure the message has a message-ID */ templatedMessage.saveChanges(); return templatedMessage; } catch (MessagingException e) { throw new TemplateBuilderException(e); } }
From source file:eu.scape_project.pw.idp.UserManager.java
/** * Method responsible for sending a email to the user, including a link to * activate his user account.// w w w .j a v a 2 s. c o m * * @param user * User the activation mail should be sent to * @param serverString * Name and port of the server the user was added. * @throws CannotSendMailException * if the mail could not be sent */ public void sendActivationMail(IdpUser user, String serverString) throws CannotSendMailException { 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(user.getEmail())); message.setSubject("Please confirm your Planningsuite user account"); StringBuilder builder = new StringBuilder(); builder.append("Dear " + user.getFirstName() + " " + user.getLastName() + ", \n\n"); builder.append("Please use the following link to confirm your Planningsuite user account: \n"); builder.append("http://" + serverString + "/idp/activateUser.jsf?uid=" + user.getActionToken()); builder.append("\n\n--\n"); builder.append("Your Planningsuite team"); message.setText(builder.toString()); message.saveChanges(); Transport.send(message); log.debug("Activation mail sent successfully to {}", user.getEmail()); } catch (Exception e) { log.error("Error at sending activation mail to {}", user.getEmail()); throw new CannotSendMailException("Error at sending activation mail to " + user.getEmail(), e); } }
From source file:eu.scape_project.pw.idp.UserManager.java
/** * Sends the user a link to reset the password. * /*from w ww. j av a2 s .c o m*/ * @param user * the user * @param serverString * host and port of the server * @throws CannotSendMailException * if the password reset mail could not be sent */ public void sendPasswordResetMail(IdpUser user, String serverString) throws CannotSendMailException { 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(user.getEmail())); message.setSubject("Planningsuite password recovery"); StringBuilder builder = new StringBuilder(); builder.append("Dear " + user.getFirstName() + " " + user.getLastName() + ", \n\n"); builder.append("You have requested help recovering the password for the Plato user "); builder.append(user.getUsername()).append(".\n\n"); builder.append("Please use the following link to reset your Planningsuite password: \n"); builder.append("http://" + serverString + "/idp/resetPassword.jsf?uid=" + user.getActionToken()); builder.append("\n\n--\n"); builder.append("Your Planningsuite team"); message.setText(builder.toString()); message.saveChanges(); Transport.send(message); log.debug("Sent password reset mail to " + user.getEmail()); } catch (Exception e) { log.error("Error at sending password reset mail to {}", user.getEmail()); throw new CannotSendMailException("Error at sending password reset mail to " + user.getEmail()); } }