List of usage examples for javax.mail.internet MimeMessage MimeMessage
public MimeMessage(MimeMessage source) throws MessagingException
source
MimeMessage. From source file:io.uengine.mail.MailAsyncService.java
@Async public void passwd(Long userId, String token, String subject, String fromUser, String fromName, final String toUser, InternetAddress[] toCC) { Session session = setMailProperties(toUser); Map model = new HashMap(); model.put("link", MessageFormatter.arrayFormat("http://www.uengine.io/auth/passwdConfirm?userid={}&token={}", new Object[] { Long.toString(userId), token }).getMessage()); String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/passwd.vm", "UTF-8", model); try {/*from ww w . j a v a 2s . co m*/ InternetAddress from = new InternetAddress(fromUser, fromName); MimeMessage message = new MimeMessage(session); message.setFrom(from); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser)); message.setSubject(subject); 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:com.app.mail.DefaultMailSender.java
private Message _populateEmailMessage(Map<SearchQuery, List<SearchResult>> searchQueryResultMap, String recipientEmailAddress, String unsubscribeToken, 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(recipientEmailAddress)); message.setSubject("New Search Results - " + MailUtil.getCurrentDate()); Map<String, Object> rootMap = new HashMap<>(); rootMap.put("emailAddress", recipientEmailAddress); rootMap.put("searchQueryResultMap", searchQueryResultMap); rootMap.put("unsubscribeToken", MailUtil.escapeUnsubscribeToken(unsubscribeToken)); rootMap.put("numberTool", new NumberTool()); rootMap.put("rootDomainName", PropertiesValues.ROOT_DOMAIN_NAME); String messageBody = VelocityEngineUtils.mergeTemplateIntoString(_velocityEngine, "template/email_body.vm", "UTF-8", rootMap); message.setContent(messageBody, "text/html"); return message; }
From source file:Mailer.java
/** Send the message. */// w w w . ja v a 2s. c o m public synchronized void doSend() throws MessagingException { if (!isComplete()) throw new IllegalArgumentException("doSend called before message was complete"); /** Properties object used to pass props into the MAIL API */ Properties props = new Properties(); props.put("mail.smtp.host", mailHost); // Create the Session object if (session == null) { session = Session.getDefaultInstance(props, null); if (verbose) session.setDebug(true); // Verbose! } // create a message final Message mesg = new MimeMessage(session); InternetAddress[] addresses; // TO Address list addresses = new InternetAddress[toList.size()]; for (int i = 0; i < addresses.length; i++) addresses[i] = new InternetAddress((String) toList.get(i)); mesg.setRecipients(Message.RecipientType.TO, addresses); // From Address mesg.setFrom(new InternetAddress(from)); // CC Address list addresses = new InternetAddress[ccList.size()]; for (int i = 0; i < addresses.length; i++) addresses[i] = new InternetAddress((String) ccList.get(i)); mesg.setRecipients(Message.RecipientType.CC, addresses); // BCC Address list addresses = new InternetAddress[bccList.size()]; for (int i = 0; i < addresses.length; i++) addresses[i] = new InternetAddress((String) bccList.get(i)); mesg.setRecipients(Message.RecipientType.BCC, addresses); // The Subject mesg.setSubject(subject); // Now the message body. mesg.setText(body); // Finally, send the message! (use static Transport method) // Do this in a Thread as it sometimes is too slow for JServ // new Thread() { // public void run() { // try { Transport.send(mesg); // } catch (MessagingException e) { // throw new IllegalArgumentException( // "Transport.send() threw: " + e.toString()); // } // } // }.start(); }
From source file:Implement.DAO.CommonDAOImpl.java
@Override public boolean sendMail(String title, String receiver, String messageContent) throws MessagingException { final String username = "registration@youtripper.com"; final String password = "Tripregister190515"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "mail.youtripper.com"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }//from w ww . java2 s. co m }); Message message = new MimeMessage(session); message.setFrom(new InternetAddress("registration@youtripper.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver)); message.setSubject(title); message.setContent(messageContent, "text/html; charset=utf-8"); Transport.send(message); return true; }
From source file:mail.MailService.java
/** * Erstellt eine MIME-Mail inkl. Transfercodierung. * @param email// w ww. java 2s. c o m * @throws MessagingException * @throws IOException */ public String createMail3(Mail email, Config config) throws MessagingException, IOException { byte[] mailAsBytes = email.getText(); byte[] outputBytes; // Transfercodierung anwenden if (config.getTranscodeDescription().equals(Config.BASE64)) { outputBytes = encodeBase64(mailAsBytes); } else if (config.getTranscodeDescription().equals(Config.QP)) { outputBytes = encodeQuotedPrintable(mailAsBytes); } else { outputBytes = mailAsBytes; } email.setText(outputBytes); Properties props = new Properties(); props.put("mail.smtp.host", "mail.java-tutor.com"); Session session = Session.getDefaultInstance(props); MimeMessage msg = new MimeMessage(session); // msg.setHeader("MIME-Version" , "1.0"); // msg.setHeader("Content-Type" , "text/plain"); // Absender InternetAddress addressFrom = new InternetAddress(email.getAbsender()); msg.setFrom(addressFrom); // Empfnger InternetAddress addressTo = new InternetAddress(email.getEmpfaenger()); msg.setRecipient(Message.RecipientType.TO, addressTo); msg.setSubject(email.getBetreff()); msg.setSentDate(email.getAbsendeDatum()); msg.setText(Utils.toString(outputBytes)); msg.saveChanges(); // Mail in Ausgabestrom schreiben ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { msg.writeTo(bOut); } catch (IOException e) { System.out.println("Fehler beim Schreiben der Mail in Schritt 3"); throw e; } // String out = bOut.toString(); // int pos1 = out.indexOf("Message-ID"); // int pos2 = out.indexOf("@localhost") + 13; // String output = out.subSequence(0, pos1).toString(); // output += (out.substring(pos2)); return removeMessageId(bOut.toString().replaceAll(ITexte.CONTENT, "Content-Transfer-Encoding: " + config.getTranscodeDescription())); }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!//from w w w .jav a 2 s .com * * @param from DOCUMENT ME! * @param to DOCUMENT ME! * @param subjectPrefix DOCUMENT ME! * @param subjectSuffix DOCUMENT ME! * @param msgText DOCUMENT ME! * @param message DOCUMENT ME! * @param session DOCUMENT ME! * * @return DOCUMENT ME! * * @throws Exception DOCUMENT ME! * @throws IllegalArgumentException DOCUMENT ME! */ public static MimeMessage createNewMessage(Address from, Address[] to, String subjectPrefix, String subjectSuffix, String msgText, MimeMessage message, Session session) throws Exception { if (from == null) { throw new IllegalArgumentException("from addres cannot be null."); } if ((to == null) || (to.length <= 0)) { throw new IllegalArgumentException("to addres cannot be null."); } if (message == null) { throw new IllegalArgumentException("to message cannot be null."); } try { //Create the message MimeMessage newMessage = new MimeMessage(session); StringBuffer buffer = new StringBuffer(); if (subjectPrefix != null) { buffer.append(subjectPrefix); } if (message.getSubject() != null) { buffer.append(message.getSubject()); } if (subjectSuffix != null) { buffer.append(subjectSuffix); } if (buffer.length() > 0) { newMessage.setSubject(buffer.toString()); } newMessage.setFrom(from); newMessage.addRecipients(Message.RecipientType.TO, to); //Create your new message part BodyPart messageBodyPart1 = new MimeBodyPart(); messageBodyPart1.setText(msgText); //Create a multi-part to combine the parts Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart1); //Create and fill part for the forwarded content BodyPart messageBodyPart2 = new MimeBodyPart(); messageBodyPart2.setDataHandler(message.getDataHandler()); //Add part to multi part multipart.addBodyPart(messageBodyPart2); //Associate multi-part with message newMessage.setContent(multipart); newMessage.saveChanges(); return newMessage; } finally { } }
From source file:com.evolveum.midpoint.notifications.impl.api.transports.MailTransport.java
@Override public void send(Message mailMessage, String transportName, Task task, OperationResult parentResult) { OperationResult result = parentResult.createSubresult(DOT_CLASS + "send"); result.addCollectionOfSerializablesAsParam("mailMessage recipient(s)", mailMessage.getTo()); result.addParam("mailMessage subject", mailMessage.getSubject()); SystemConfigurationType systemConfiguration = NotificationsUtil .getSystemConfiguration(cacheRepositoryService, new OperationResult("dummy")); if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null || systemConfiguration.getNotificationConfiguration().getMail() == null) { String msg = "No notifications are configured. Mail notification to " + mailMessage.getTo() + " will not be sent."; LOGGER.warn(msg);/*from w w w. ja v a 2 s . co m*/ result.recordWarning(msg); return; } MailConfigurationType mailConfigurationType = systemConfiguration.getNotificationConfiguration().getMail(); String redirectToFile = mailConfigurationType.getRedirectToFile(); if (redirectToFile != null) { try { TransportUtil.appendToFile(redirectToFile, formatToFile(mailMessage)); result.recordSuccess(); } catch (IOException e) { LoggingUtils.logException(LOGGER, "Couldn't write to mail redirect file {}", e, redirectToFile); result.recordPartialError("Couldn't write to mail redirect file " + redirectToFile, e); } return; } if (mailConfigurationType.getServer().isEmpty()) { String msg = "Mail server(s) are not defined, mail notification to " + mailMessage.getTo() + " will not be sent."; LOGGER.warn(msg); result.recordWarning(msg); return; } long start = System.currentTimeMillis(); String from = mailConfigurationType.getDefaultFrom() != null ? mailConfigurationType.getDefaultFrom() : "nobody@nowhere.org"; for (MailServerConfigurationType mailServerConfigurationType : mailConfigurationType.getServer()) { OperationResult resultForServer = result.createSubresult(DOT_CLASS + "send.forServer"); final String host = mailServerConfigurationType.getHost(); resultForServer.addContext("server", host); resultForServer.addContext("port", mailServerConfigurationType.getPort()); Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); if (mailServerConfigurationType.getPort() != null) { properties.setProperty("mail.smtp.port", String.valueOf(mailServerConfigurationType.getPort())); } MailTransportSecurityType mailTransportSecurityType = mailServerConfigurationType .getTransportSecurity(); boolean sslEnabled = false, starttlsEnable = false, starttlsRequired = false; switch (mailTransportSecurityType) { case STARTTLS_ENABLED: starttlsEnable = true; break; case STARTTLS_REQUIRED: starttlsEnable = true; starttlsRequired = true; break; case SSL: sslEnabled = true; break; } properties.put("mail.smtp.ssl.enable", "" + sslEnabled); properties.put("mail.smtp.starttls.enable", "" + starttlsEnable); properties.put("mail.smtp.starttls.required", "" + starttlsRequired); if (Boolean.TRUE.equals(mailConfigurationType.isDebug())) { properties.put("mail.debug", "true"); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Using mail properties: "); for (Object key : properties.keySet()) { if (key instanceof String && ((String) key).startsWith("mail.")) { LOGGER.debug(" - " + key + " = " + properties.get(key)); } } } task.recordState("Sending notification mail via " + host); Session session = Session.getInstance(properties); try { MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(new InternetAddress(from)); for (String recipient : mailMessage.getTo()) { mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient)); } mimeMessage.setSubject(mailMessage.getSubject(), "utf-8"); String contentType = mailMessage.getContentType(); if (StringUtils.isEmpty(contentType)) { contentType = "text/plain; charset=UTF-8"; } mimeMessage.setContent(mailMessage.getBody(), contentType); javax.mail.Transport t = session.getTransport("smtp"); if (StringUtils.isNotEmpty(mailServerConfigurationType.getUsername())) { ProtectedStringType passwordProtected = mailServerConfigurationType.getPassword(); String password = null; if (passwordProtected != null) { try { password = protector.decryptString(passwordProtected); } catch (EncryptionException e) { String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", because the plaintext password value couldn't be obtained. Trying another mail server, if there is any."; LoggingUtils.logException(LOGGER, msg, e); resultForServer.recordFatalError(msg, e); continue; } } t.connect(mailServerConfigurationType.getUsername(), password); } else { t.connect(); } t.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); LOGGER.info("Message sent successfully to " + mailMessage.getTo() + " via server " + host + "."); resultForServer.recordSuccess(); result.recordSuccess(); long duration = System.currentTimeMillis() - start; task.recordState( "Notification mail sent successfully via " + host + ", in " + duration + " ms overall."); task.recordNotificationOperation(NAME, true, duration); return; } catch (MessagingException e) { String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", trying another mail server, if there is any"; LoggingUtils.logException(LOGGER, msg, e); resultForServer.recordFatalError(msg, e); task.recordState("Error sending notification mail via " + host); } } LOGGER.warn( "No more mail servers to try, mail notification to " + mailMessage.getTo() + " will not be sent."); result.recordWarning("Mail notification to " + mailMessage.getTo() + " could not be sent."); task.recordNotificationOperation(NAME, false, System.currentTimeMillis() - start); }
From source file:ru.org.linux.exception.ExceptionResolver.java
/** * ? E-mail ?.// w ww . j a v a 2s . com * * @param request ? web- * @param exception ? * @return , ? ??? ? ? */ private String sendEmailToAdmin(HttpServletRequest request, Exception exception) { InternetAddress mail; String adminEmailAddress = configuration.getAdminEmailAddress(); try { mail = new InternetAddress(adminEmailAddress, true); } catch (AddressException e) { return EMAIL_NOT_SENT + " ? e-mail ?: " + adminEmailAddress; } StringBuilder text = new StringBuilder(); if (exception.getMessage() == null) { text.append(exception.getClass().getName()); } else { text.append(exception.getMessage()); } text.append("\n\n"); Template tmpl = Template.getTemplate(request); // text.append("Main URL: ").append(tmpl.getMainUrl()).append(request.getAttribute("javax.servlet.error.request_uri")); String mainUrl = "<unknown>"; mainUrl = configuration.getMainUrl(); text.append("Main URL: ").append(mainUrl).append(request.getServletPath()); if (request.getQueryString() != null) { text.append('?').append(request.getQueryString()).append('\n'); } text.append('\n'); text.append("IP: " + request.getRemoteAddr() + '\n'); text.append(" Headers: "); Enumeration enu = request.getHeaderNames(); while (enu.hasMoreElements()) { String paramName = (String) enu.nextElement(); text.append("\n ").append(paramName).append(": ").append(request.getHeader(paramName)); } text.append("\n\n"); StringWriter exceptionStackTrace = new StringWriter(); exception.printStackTrace(new PrintWriter(exceptionStackTrace)); text.append(exceptionStackTrace.toString()); Properties props = new Properties(); props.put("mail.smtp.host", "localhost"); Session mailSession = Session.getDefaultInstance(props, null); MimeMessage emailMessage = new MimeMessage(mailSession); try { emailMessage.setFrom(new InternetAddress("no-reply@linux.org.ru")); emailMessage.addRecipient(Message.RecipientType.TO, mail); emailMessage.setSubject("Linux.org.ru: " + exception.getClass()); emailMessage.setSentDate(new Date()); emailMessage.setText(text.toString(), "UTF-8"); } catch (Exception e) { logger.error("An error occured while creating e-mail!", e); return EMAIL_NOT_SENT; } try { Transport.send(emailMessage); return EMAIL_SENT; } catch (Exception e) { return EMAIL_NOT_SENT; } }
From source file:com.mgmtp.perfload.perfalyzer.reporting.email.EmailReporter.java
private void sendMessage(final String subject, final String content) { try {//from www . java 2 s .c o m Session session = (authenticator != null) ? Session.getInstance(smtpProps, authenticator) : Session.getInstance(smtpProps); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromAddress)); msg.setSubject(subject); msg.addRecipients(Message.RecipientType.TO, on(',').join(toAddresses)); msg.setText(content, UTF_8.name(), "html"); Transport.send(msg); } catch (MessagingException e) { log.error("Error while creating report e-mail", e); } }
From source file:davmail.smtp.TestSmtp.java
public void testBccMessage() throws IOException, MessagingException, InterruptedException { MimeMessage mimeMessage = new MimeMessage((Session) null); mimeMessage.addHeader("to", Settings.getProperty("davmail.to")); mimeMessage.setSubject("Test subject dav"); mimeMessage.setText("Test message"); sendAndCheckMessage(mimeMessage, Settings.getProperty("davmail.bcc")); }