List of usage examples for javax.mail.internet MimeMessage addRecipient
public void addRecipient(RecipientType type, Address address) throws MessagingException
From source file:ru.org.linux.user.LostPasswordController.java
private void sendEmail(User user, String email, Timestamp resetDate) throws MessagingException { Properties props = new Properties(); props.put("mail.smtp.host", "localhost"); Session mailSession = Session.getDefaultInstance(props, null); MimeMessage msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress("no-reply@linux.org.ru")); String resetCode = UserService.getResetCode(configuration.getSecret(), user.getNick(), email, resetDate); msg.addRecipient(RecipientType.TO, new InternetAddress(email)); msg.setSubject("Your password @linux.org.ru"); msg.setSentDate(new Date()); msg.setText("?!\n\n" + "? ?? ? ?? http://www.linux.org.ru/reset-password\n\n" + " " + user.getNick() + ", ?: " + resetCode + "\n\n" + "!"); Transport.send(msg);//from www .j a v a2 s.c om }
From source file:com.hiperium.bo.manager.mail.EmailMessageManager.java
/** * Sends an email with the new user password. * //from w w w .j a v a 2s .c o m * @param user * @throws javax.mail.internet.AddressException * @throws javax.mail.MessagingException */ public void sendNewPassword(User user) { try { this.log.debug("sendNewPassword() - START"); // Create the corresponding user locale. Locale locale = null; if (StringUtils.isBlank(user.getLanguageId())) { locale = Locale.getDefault(); } else { locale = new Locale(user.getLanguageId()); } ResourceBundle resource = ResourceBundle.getBundle(EnumI18N.COMMON.value(), locale); // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", CloudEmailUser.HOST); properties.setProperty("mail.user", CloudEmailUser.USERNAME); properties.setProperty("mail.password", CloudEmailUser.PASSWORD); // Get the default Session object. Session session = Session.getDefaultInstance(properties); // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(CloudEmailUser.ADDRESS)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail())); // Set Subject: header field message.setSubject(resource.getString(GENERATED_USER_PASSWD_SUBJECT)); // Send the actual HTML message, as big as you like message.setContent(MessageFormat.format(resource.getString(GENERATED_USER_PASSWD_CONTENT), user.getFirstname(), user.getLastname(), user.getPassword()), "text/html"); // Send message Transport.send(message); this.log.debug("sendNewPassword() - END"); } catch (AddressException e) { this.log.error("AddressException to send email to " + user.getEmail(), e); } catch (MessagingException e) { this.log.error("MessagingException to send email to " + user.getEmail(), e); } }
From source file:com.autentia.tnt.mail.DefaultMailService.java
public void sendFiles(String to, String subject, String text, Collection<File> attachments) throws MessagingException { MimeMessage message = new MimeMessage(session); Transport t = session.getTransport("smtp"); message.setFrom(new InternetAddress(configurationUtil.getMailUsername())); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject);/* w w w. j a v a 2 s. c om*/ message.setSentDate(new Date()); if (attachments == null || attachments.size() < 1) { message.setText(text); } else { // create the message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(text); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); for (File attachment : attachments) { messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachment); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachment.getName()); multipart.addBodyPart(messageBodyPart); } message.setContent(multipart); } t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword()); t.sendMessage(message, message.getAllRecipients()); t.close(); }
From source file:cz.filmtit.userspace.Emailer.java
/** * Sends an email with parameters that has been collected before in the fields of the class. * @return Sign if the email has been successfully sent *//* w w w . j a v a 2 s . c o m*/ public boolean send() { if (hasCollectedData()) { // send mail; javax.mail.Session session; logger.info("Emailer", "Create session for mail login " + (String) configuration.getProperty("mail.filmtit.address") + " password" + (String) configuration.getProperty("mail.filmtit.password")); session = javax.mail.Session.getDefaultInstance(configuration, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication((String) configuration.getProperty("mail.filmtit.address"), (String) configuration.getProperty("mail.filmtit.password")); } }); session.setDebug(true); javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(session); try { message.addRecipient(Message.RecipientType.TO, new InternetAddress(this.email)); message.setFrom(new InternetAddress((String) configuration.getProperty("mail.filmtit.address"))); message.setSubject(this.subject); message.setText(this.message); Transport transportSSL = session.getTransport(); transportSSL.connect((String) configuration.getProperty("mail.smtps.host"), Integer.parseInt(configuration.getProperty("mail.smtps.port")), (String) configuration.getProperty("mail.filmtit.address"), (String) configuration.getProperty("mail.filmtit.password")); // account used transportSSL.sendMessage(message, message.getAllRecipients()); transportSSL.close(); } catch (MessagingException ex) { logger.error("Emailer", "An error while sending an email. " + ex); } return true; } logger.warning("Emailer", "Emailer has not collected all data to be able to send an email."); return false; }
From source file:org.codice.alliance.core.email.impl.EmailSenderImpl.java
/** sendEmail method sends email after receiving input parameters */ @Override/*w ww. j a v a2 s . c o m*/ public void sendEmail(String fromEmail, String toEmail, String subject, String body, List<Pair<String, InputStream>> attachments) throws IOException { notNull(fromEmail, "fromEmail must be non-null"); notNull(toEmail, "toEmail must be non-null"); notNull(subject, "subject must be non-null"); notNull(body, "body must be non-null"); notNull(attachments, "attachments must be non-null"); if (StringUtils.isBlank(mailHost)) { throw new IOException("the mail server hostname has not been configured"); } List<File> tempFiles = new LinkedList<>(); try { InternetAddress emailAddr = new InternetAddress(toEmail); emailAddr.validate(); Properties properties = createSessionProperties(); Session session = Session.getDefaultInstance(properties); MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(new InternetAddress(fromEmail)); mimeMessage.addRecipient(Message.RecipientType.TO, emailAddr); mimeMessage.setSubject(subject); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); Holder<Long> bytesWritten = new Holder<>(0L); for (Pair<String, InputStream> attachment : attachments) { messageBodyPart = new MimeBodyPart(); File file = File.createTempFile("email-sender-", ".dat"); tempFiles.add(file); copyDataToTempFile(file, attachment.getValue(), bytesWritten); messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(file))); messageBodyPart.setFileName(attachment.getKey()); multipart.addBodyPart(messageBodyPart); } mimeMessage.setContent(multipart); send(mimeMessage); LOGGER.debug("Email sent to " + toEmail); } catch (AddressException e) { throw new IOException("invalid email address: email=" + toEmail, e); } catch (MessagingException e) { throw new IOException("message error occurred on send", e); } finally { tempFiles.forEach(file -> { if (!file.delete()) { LOGGER.debug("unable to delete tmp file: path={}", file); } }); } }
From source file:org.codice.ddf.catalog.ui.query.FeedbackApplication.java
@Override public void init() { post("/feedback", APPLICATION_JSON, (req, res) -> { if (StringUtils.isNotEmpty(emailDestination)) { FeedbackRequest feedback = parseFeedbackRequest(util.safeGetBody(req)); feedback.setAuthUsername(getCurrentUser()); String emailSubject = getEmailSubject(feedback); String emailBody = getEmailBody(feedback); if (emailBody != null) { emailBody = emailBody.replaceAll("\\\\n", "\n"); } else { emailBody = "<html/>"; }/* w ww .ja v a 2s. c o m*/ Session emailSession = smtpClient.createSession(); MimeMessage message = new MimeMessage(emailSession); message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailDestination)); message.setSubject(emailSubject); message.setContent(emailBody, "text/html; charset=utf-8"); smtpClient.send(message); res.body("{}"); res.status(200); return res; } else { res.status(500); res.body("No destination email configured, feedback cannot be submitted."); LOGGER.debug("Feedback submission failed, destination email is not configured."); return res; } }); exception(Exception.class, (e, request, response) -> { response.status(500); response.body("Error submitting feedback"); LOGGER.debug("Feedback submission failed", e); }); enableRouteOverview(); }
From source file:app.logica.gestores.GestorEmail.java
/** * Create a MimeMessage using the parameters provided. * * @param to/*from www. ja v a 2 s. co m*/ * Email address of the receiver. * @param from * Email address of the sender, the mailbox account. * @param subject * Subject of the email. * @param bodyText * Body text of the email. * @param file * Path to the file to be attached. * @return MimeMessage to be used to send email. * @throws MessagingException */ private MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText, File file) throws MessagingException, IOException { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); email.setFrom(new InternetAddress(from)); email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); email.setSubject(subject); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(bodyText, "text/plain"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); mimeBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(file); mimeBodyPart.setDataHandler(new DataHandler(source)); mimeBodyPart.setFileName(file.getName()); multipart.addBodyPart(mimeBodyPart); email.setContent(multipart); return email; }
From source file:com.autentia.tnt.mail.DefaultMailService.java
public void sendOutputStreams(String to, String subject, String text, Map<InputStream, String> attachments) throws MessagingException { Transport t = null;//ww w . j a va 2 s . c o m try { MimeMessage message = new MimeMessage(session); t = session.getTransport("smtp"); message.setFrom(new InternetAddress(configurationUtil.getMailUsername())); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setSentDate(new Date()); if (attachments == null || attachments.size() < 1) { message.setText(text); } else { // create the message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(text); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); try { for (InputStream attachment : attachments.keySet()) { messageBodyPart = new MimeBodyPart(); DataSource source = new ByteArrayDataSource(attachment, "application/octet-stream"); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachments.get(attachment)); //NOSONAR multipart.addBodyPart(messageBodyPart); //Se emplea keyset y no valueset porque se emplea tanto la key como el val } } catch (IOException e) { throw new MessagingException("cannot add an attachment to mail", e); } message.setContent(multipart); } t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword()); t.sendMessage(message, message.getAllRecipients()); } finally { if (t != null) { t.close(); } } }
From source file:net.ymate.module.mailsender.impl.DefaultMailSendProvider.java
@Override public IMailSendBuilder create(final MailSendServerCfgMeta serverCfgMeta) { return new AbstractMailSendBuilder() { @Override//w w w. j av a 2s .c o m public void send(final String content) throws Exception { __sendExecPool.execute(new Runnable() { @Override public void run() { try { MimeMessage _message = new MimeMessage(serverCfgMeta.createIfNeed()); // for (String _to : getTo()) { _message.addRecipient(Message.RecipientType.TO, new InternetAddress(_to)); } for (String _cc : getCc()) { _message.addRecipient(Message.RecipientType.CC, new InternetAddress(_cc)); } for (String _bcc : getBcc()) { _message.addRecipient(Message.RecipientType.BCC, new InternetAddress(_bcc)); } // if (getLevel() != null) { switch (getLevel()) { case LEVEL_HIGH: _message.setHeader("X-MSMail-Priority", "High"); _message.setHeader("X-Priority", "1"); break; case LEVEL_NORMAL: _message.setHeader("X-MSMail-Priority", "Normal"); _message.setHeader("X-Priority", "3"); break; case LEVEL_LOW: _message.setHeader("X-MSMail-Priority", "Low"); _message.setHeader("X-Priority", "5"); break; default: } } // String _charset = StringUtils.defaultIfEmpty(getCharset(), "UTF-8"); _message.setFrom(new InternetAddress(serverCfgMeta.getFromAddr(), serverCfgMeta.getDisplayName(), _charset)); _message.setSubject(getSubject(), _charset); // Multipart _container = new MimeMultipart(); // MimeBodyPart _textBodyPart = new MimeBodyPart(); if (getMimeType() == null) { mimeType(IMailSender.MimeType.TEXT_PLAIN); } _textBodyPart.setContent(content, getMimeType().getMimeType() + ";charset=" + _charset); _container.addBodyPart(_textBodyPart); // ??<img src="cid:<CID_NAME>"> for (PairObject<String, File> _file : getAttachments()) { if (_file.getValue() != null) { MimeBodyPart _fileBodyPart = new MimeBodyPart(); FileDataSource _fileDS = new FileDataSource(_file.getValue()); _fileBodyPart.setDataHandler(new DataHandler(_fileDS)); if (_file.getKey() != null) { _fileBodyPart.setHeader("Content-ID", _file.getKey()); } _fileBodyPart.setFileName(_fileDS.getName()); _container.addBodyPart(_fileBodyPart); } } // ?? _message.setContent(_container); Transport.send(_message); } catch (Exception e) { throw new RuntimeException(RuntimeUtils.unwrapThrow(e)); } } }); } }; }
From source file:be.fedict.eid.pkira.blm.model.mail.MailHandlerBean.java
@Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void onMessage(Message arg0) { ObjectMessage objectMessage = (ObjectMessage) arg0; try {/*from www. j av a2s . c o m*/ Mail mail = (Mail) objectMessage.getObject(); // Get properties String mailProtocol = getMailProtocol(); String mailServer = getSmtpServer(); String mailUser = getSmtpUser(); String mailPort = getSmtpPort(); String mailPassword = getSmtpPassword(); // Initialize a mail session Properties props = new Properties(); props.put("mail." + mailProtocol + ".host", mailServer); props.put("mail." + mailProtocol + ".port", mailPort); Session session = Session.getInstance(props); // Create the message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(mail.getSender())); for (String recipient : mail.getRecipients()) { msg.addRecipient(RecipientType.TO, new InternetAddress(recipient)); } msg.setSubject(mail.getSubject(), "UTF-8"); Multipart multipart = new MimeMultipart(); msg.setContent(multipart); // Set the email message text and attachment MimeBodyPart messagePart = new MimeBodyPart(); messagePart.setContent(mail.getBody(), mail.getContentType()); multipart.addBodyPart(messagePart); if (mail.getAttachmentData() != null) { ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(mail.getAttachmentData(), mail.getAttachmentContentType()); DataHandler dataHandler = new DataHandler(byteArrayDataSource); MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setDataHandler(dataHandler); attachmentPart.setFileName(mail.getAttachmentFileName()); multipart.addBodyPart(attachmentPart); } // Open transport and send message Transport transport = session.getTransport(mailProtocol); if (StringUtils.isNotBlank(mailUser)) { transport.connect(mailUser, mailPassword); } else { transport.connect(); } msg.saveChanges(); transport.sendMessage(msg, msg.getAllRecipients()); } catch (JMSException e) { errorLogger.logError(ApplicationComponent.MAIL, "Cannot handle the object message from the queue", e); throw new RuntimeException(e); } catch (MessagingException e) { errorLogger.logError(ApplicationComponent.MAIL, "Cannot send a mail message", e); throw new RuntimeException(e); } }