List of usage examples for javax.mail.internet MimeMessage setText
@Override public void setText(String text, String charset) throws MessagingException
From source file:com.szmslab.quickjavamail.send.MailSender.java
/** * ?????/*w w w.j a v a 2 s . co m*/ * * @param message * * @throws MessagingException * @throws UnsupportedEncodingException */ private void setContent(MimeMessage message) throws MessagingException, UnsupportedEncodingException { if (StringUtils.isBlank(html)) { if (attachmentFileList.isEmpty()) { /* * text/plain */ message.setText(text, charset); } else { /* * multipart/mixed * text/plain * attachment */ Multipart mixedMultipart = createMixedMimeMultipart(); mixedMultipart.addBodyPart(createTextPart()); for (AttachmentFile file : attachmentFileList) { mixedMultipart.addBodyPart(createAttachmentPart(file)); } message.setContent(mixedMultipart); } } else { if (attachmentFileList.isEmpty()) { if (inlineImageFileList.isEmpty()) { /* * multipart/alternative * text/plain * text/html */ Multipart alternativeMultipart = createAlternativeMimeMultipart(); alternativeMultipart.addBodyPart(createTextPart()); alternativeMultipart.addBodyPart(createHtmlPart()); message.setContent(alternativeMultipart); } else { /* * multipart/alternative * text/plain * mulpart/related * text/html * image */ Multipart relatedMultipart = createRelatedMimeMultipart(); relatedMultipart.addBodyPart(createHtmlPart()); for (InlineImageFile file : inlineImageFileList) { relatedMultipart.addBodyPart(createImagePart(file)); } MimeBodyPart relatedPart = new MimeBodyPart(); relatedPart.setContent(relatedMultipart); Multipart alternativeMultipart = createAlternativeMimeMultipart(); alternativeMultipart.addBodyPart(createTextPart()); alternativeMultipart.addBodyPart(relatedPart); message.setContent(alternativeMultipart); } } else { if (inlineImageFileList.isEmpty()) { /* * multipart/mixed * mulpart/alternative * text/plain * text/html * attachment */ Multipart alternativeMultipart = createAlternativeMimeMultipart(); alternativeMultipart.addBodyPart(createTextPart()); alternativeMultipart.addBodyPart(createHtmlPart()); MimeBodyPart alternativePart = new MimeBodyPart(); alternativePart.setContent(alternativeMultipart); Multipart mixedMultipart = createMixedMimeMultipart(); mixedMultipart.addBodyPart(alternativePart); for (AttachmentFile file : attachmentFileList) { mixedMultipart.addBodyPart(createAttachmentPart(file)); } message.setContent(mixedMultipart); } else { /* * multipart/mixed * mulpart/alternative * text/plain * mulpart/related * text/html * image * attachment */ Multipart relatedMultipart = createRelatedMimeMultipart(); relatedMultipart.addBodyPart(createHtmlPart()); for (InlineImageFile file : inlineImageFileList) { relatedMultipart.addBodyPart(createImagePart(file)); } MimeBodyPart relatedPart = new MimeBodyPart(); relatedPart.setContent(relatedMultipart); Multipart alternativeMultipart = createAlternativeMimeMultipart(); alternativeMultipart.addBodyPart(createTextPart()); alternativeMultipart.addBodyPart(relatedPart); MimeBodyPart alternativePart = new MimeBodyPart(); alternativePart.setContent(alternativeMultipart); Multipart mixedMultipart = createMixedMimeMultipart(); mixedMultipart.addBodyPart(alternativePart); for (AttachmentFile file : attachmentFileList) { mixedMultipart.addBodyPart(createAttachmentPart(file)); } message.setContent(mixedMultipart); } } } setHeaderToPart(message); }
From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java
public String sendMail() { try {/*from ww w .j a v a 2 s . com*/ Properties props = new Properties(); // Server if (smtpServer == null || smtpServer.equals("")) { log.info("samigo.email.smtpServer is not set"); smtpServer = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService"); if (smtpServer == null || smtpServer.equals("")) { log.info("smtp@org.sakaiproject.email.api.EmailService is not set"); log.error( "Please set the value of samigo.email.smtpServer or smtp@org.sakaiproject.email.api.EmailService"); return "error"; } } props.setProperty("mail.smtp.host", smtpServer); // Port if (smtpPort == null || smtpPort.equals("")) { log.warn("samigo.email.smtpPort is not set. The default port 25 will be used."); } else { props.setProperty("mail.smtp.port", smtpPort); } props.put("mail.smtp.sendpartial", "true"); Session session = Session.getInstance(props, null); session.setDebug(true); MimeMessage msg = new MimeMessage(session); InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName); msg.setFrom(fromIA); //msg.addHeaderLine("Subject: " + subject); msg.setSubject(subject, "UTF-8"); String noReplyEmaillAddress = ServerConfigurationService.getString("setup.request", "no-reply@" + ServerConfigurationService.getServerName()); msg.addHeaderLine("To: " + noReplyEmaillAddress); msg.setText(message, "UTF-8"); msg.addHeaderLine("Content-Type: text/html"); ArrayList<InternetAddress> toIAList = new ArrayList<InternetAddress>(); String email = ""; Iterator iter = toEmailAddressList.iterator(); while (iter.hasNext()) { try { email = (String) iter.next(); toIAList.add(new InternetAddress(email)); } catch (AddressException ae) { log.error("invalid email address: " + email); } } InternetAddress[] toIA = new InternetAddress[toIAList.size()]; int count = 0; Iterator iter2 = toIAList.iterator(); while (iter2.hasNext()) { toIA[count++] = (InternetAddress) iter2.next(); } try { Transport transport = session.getTransport("smtp"); msg.saveChanges(); transport.connect(); try { transport.sendMessage(msg, toIA); } catch (SendFailedException e) { log.debug("SendFailedException: " + e); return "error"; } catch (MessagingException e) { log.warn("1st MessagingException: " + e); return "error"; } transport.close(); } catch (MessagingException e) { log.warn("2nd MessagingException:" + e); return "error"; } } catch (UnsupportedEncodingException ue) { log.warn("UnsupportedEncodingException:" + ue); ue.printStackTrace(); } catch (MessagingException me) { log.warn("3rd MessagingException:" + me); return "error"; } return "send"; }
From source file:org.bibsonomy.util.MailUtils.java
/** * Sends a mail to the given recipients/*from ww w.ja v a 2 s. c o m*/ * * @param recipients * @param subject * @param message * @param from * @throws MessagingException */ private void sendMail(final String[] recipients, final String subject, final String message, final String from) throws MessagingException { boolean debug = false; // create some properties and get the default Session final Session session = Session.getDefaultInstance(props, null); session.setDebug(debug); // create a message final MimeMessage msg = new MimeMessage(session); // set the from and to address final InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); final 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); // Optional : You can also set your custom headers in the Email if you Want //msg.addHeader("X-Sent-By", "Bibsonomy-Bot"); // Setting the Subject and Content Type msg.setSubject(subject); msg.setText(message, "UTF-8"); Transport.send(msg); }
From source file:org.squale.squalecommon.util.mail.javamail.JavaMailProviderImpl.java
/** * This method send mail/*from w w w . j av a2s.c om*/ * * @param sender Sender Address * @param recipients List of recipient address * @param subject Subject of the mail * @param content Content of the mail * @throws MailException Exception happened the send of the mail */ public void sendMail(String sender, String[] recipients, String subject, String content) throws MailException { // Initialization of the mail provider init(); // if there is mail configuration information if (smtpServer != null && (senderAddress != null || sender != null)) { // Properties used for sending mails Properties props = System.getProperties(); props.put("mail.smtp.host", smtpServer); Session session = smtpAuthent(props); // Header message definition MimeMessage message = new MimeMessage(session); try { // If a sender argument is not null we use it if (sender != null) { message.setFrom(new InternetAddress(sender)); } // If the sender argument is null else { message.setFrom(new InternetAddress(senderAddress)); } // We send to each recipient for (int i = 0; i <= recipients.length - 1; i++) { String mailAddress = (String) recipients[i]; LOG.debug("Recipent : " + recipients[i]); message.addRecipient(Message.RecipientType.BCC, new InternetAddress(mailAddress)); } // Body message definition message.setSubject(subject); message.setText(content, "iso-8859-1"); // Send of the mail Transport.send(message); } catch (AddressException e) { throw new MailException(e); } catch (MessagingException e) { throw new MailException(e); } } else { String message = MailMessages.getString("mail.exception.noConfig"); throw new MailException(message); } }
From source file:com.stratelia.silverpeas.notificationserver.channel.smtp.SMTPListener.java
/** * send email to destination using SMTP protocol and JavaMail 1.3 API (compliant with MIME * format)./* w ww.jav a 2 s. c om*/ * * @param pFrom : from field that will appear in the email header. * @param personalName : * @see {@link InternetAddress} * @param pTo : the email target destination. * @param pSubject : the subject of the email. * @param pMessage : the message or payload of the email. */ private void sendEmail(String pFrom, String personalName, String pTo, String pSubject, String pMessage, boolean htmlFormat) throws NotificationServerException { // retrieves system properties and set up Delivery Status Notification // @see RFC1891 Properties properties = System.getProperties(); properties.put("mail.smtp.host", getMailServer()); properties.put("mail.smtp.auth", String.valueOf(isAuthenticated())); javax.mail.Session session = javax.mail.Session.getInstance(properties, null); session.setDebug(isDebug()); // print on the console all SMTP messages. Transport transport = null; try { InternetAddress fromAddress = getAuthorizedEmailAddress(pFrom, personalName); InternetAddress replyToAddress = null; InternetAddress[] toAddress = null; // parsing destination address for compliance with RFC822 try { toAddress = InternetAddress.parse(pTo, false); if (!AdminReference.getAdminService().getAdministratorEmail().equals(pFrom) && (!fromAddress.getAddress().equals(pFrom) || isForceReplyToSenderField())) { replyToAddress = new InternetAddress(pFrom, false); if (StringUtil.isDefined(personalName)) { replyToAddress.setPersonal(personalName, CharEncoding.UTF_8); } } } catch (AddressException e) { SilverTrace.warn("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE", "From = " + pFrom + ", To = " + pTo); } MimeMessage email = new MimeMessage(session); email.setFrom(fromAddress); if (replyToAddress != null) { email.setReplyTo(new InternetAddress[] { replyToAddress }); } email.setRecipients(javax.mail.Message.RecipientType.TO, toAddress); email.setHeader("Precedence", "list"); email.setHeader("List-ID", fromAddress.getAddress()); String subject = pSubject; if (subject == null) { subject = ""; } String content = pMessage; if (content == null) { content = ""; } email.setSubject(subject, CharEncoding.UTF_8); if (content.toLowerCase().contains("<html>") || htmlFormat) { email.setContent(content, "text/html; charset=\"UTF-8\""); } else { email.setText(content, CharEncoding.UTF_8); } email.setSentDate(new Date()); // create a Transport connection (TCP) if (isSecure()) { transport = session.getTransport(SECURE_TRANSPORT); } else { transport = session.getTransport(SIMPLE_TRANSPORT); } if (isAuthenticated()) { SilverTrace.info("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE", "Host = " + getMailServer() + " Port=" + getPort() + " User=" + getLogin()); transport.connect(getMailServer(), getPort(), getLogin(), getPassword()); } else { transport.connect(); } transport.sendMessage(email, toAddress); } catch (MessagingException e) { Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e); } catch (UnsupportedEncodingException e) { Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e); } catch (Exception e) { throw new NotificationServerException("SMTPListner.sendEmail()", SilverpeasException.ERROR, "smtp.EX_CANT_SEND_SMTP_MESSAGE", e); } finally { if (transport != null) { try { transport.close(); } catch (Exception e) { SilverTrace.error("smtp", "SMTPListner.sendEmail()", "root.EX_IGNORED", "ClosingTransport", e); } } } }
From source file:edu.harvard.iq.dataverse.MailServiceBean.java
public void sendMail(String from, String to, String subject, String messageText, Map<Object, Object> extraHeaders) { try {/* w w w.j a v a 2 s . c o m*/ MimeMessage msg = new MimeMessage(session); if (from.matches(EMAIL_PATTERN)) { msg.setFrom(new InternetAddress(from)); } else { // set fake from address; instead, add it as part of the message //msg.setFrom(new InternetAddress("invalid.email.address@mailinator.com")); msg.setFrom(getSystemAddress()); messageText = "From: " + from + "\n\n" + messageText; } msg.setSentDate(new Date()); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); msg.setSubject(subject, charset); msg.setText(messageText, charset); if (extraHeaders != null) { for (Object key : extraHeaders.keySet()) { String headerName = key.toString(); String headerValue = extraHeaders.get(key).toString(); msg.addHeader(headerName, headerValue); } } Transport.send(msg); } catch (AddressException ae) { ae.printStackTrace(System.out); } catch (MessagingException me) { me.printStackTrace(System.out); } }
From source file:org.jenkinsci.plugins.send_mail_builder.SendMailBuilder.java
@Override public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener) throws IOException, InterruptedException { final EnvVars env = build.getEnvironment(listener); final String charset = Mailer.descriptor().getCharset(); final MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession()); try {/*from www . j a v a 2s . c o m*/ msg.setFrom(Mailer.StringToAddress(JenkinsLocationConfiguration.get().getAdminAddress(), charset)); msg.setContent("", "text/plain"); msg.setSentDate(new Date()); String actualReplyTo = env.expand(replyTo); if (StringUtils.isBlank(actualReplyTo)) { actualReplyTo = Mailer.descriptor().getReplyToAddress(); } if (StringUtils.isNotBlank(actualReplyTo)) { msg.setReplyTo(new Address[] { Mailer.StringToAddress(actualReplyTo, charset) }); } msg.setRecipients(RecipientType.TO, toInternetAddresses(listener, env.expand(tos), charset)); msg.setRecipients(RecipientType.CC, toInternetAddresses(listener, env.expand(ccs), charset)); msg.setRecipients(RecipientType.BCC, toInternetAddresses(listener, env.expand(bccs), charset)); msg.setSubject(env.expand(subject), charset); msg.setText(env.expand(text), charset); Transport.send(msg); } catch (final MessagingException e) { listener.getLogger().println(Messages.SendMail_FailedToSend()); e.printStackTrace(listener.error(e.getMessage())); return false; } listener.getLogger().println(Messages.SendMail_SentSuccessfully()); return true; }
From source file:edu.harvard.iq.dataverse.MailServiceBean.java
public void sendMail(String host, String from, String to, String subject, String messageText) { Properties props = System.getProperties(); props.put("mail.smtp.host", host); Session session = Session.getDefaultInstance(props, null); try {/*from w w w . ja v a2s . co m*/ MimeMessage msg = new MimeMessage(session); String[] recipientStrings = to.split(","); InternetAddress[] recipients = new InternetAddress[recipientStrings.length]; try { msg.setFrom(new InternetAddress(from, charset)); for (int i = 0; i < recipients.length; i++) { recipients[i] = new InternetAddress(recipientStrings[i], "", charset); } } catch (UnsupportedEncodingException ex) { logger.severe(ex.getMessage()); } msg.setRecipients(Message.RecipientType.TO, recipients); msg.setSubject(subject, charset); msg.setText(messageText, charset); Transport.send(msg, recipients); } catch (AddressException ae) { ae.printStackTrace(System.out); } catch (MessagingException me) { me.printStackTrace(System.out); } }
From source file:org.opens.kbaccess.controller.utils.AMailerController.java
/** * Send a mail to the specified recipients. * //from www.ja v a 2s. c o m * @param subject The mail's subject * @param message The mail's body * @param recipients The adressee * @return true if the send succeed, * false otherwise */ public boolean sendMail(String subject, String message, String[] recipients) { Session session; MimeMessage mimeMessage; Properties properties; // sanity check if (recipients.length == 0) { return true; } // set-up session properties = new Properties(); properties.put("mail.smtp.host", mailingServiceProperties.getSmtpHost()); session = Session.getDefaultInstance(properties); //session.setDebug(true); try { Address from; Address[] to = new InternetAddress[recipients.length]; // set sender from = new InternetAddress(mailingServiceProperties.getDefaultReturnAddress()); // initialize recipients list for (int i = 0; i < to.length; ++i) { to[i] = new InternetAddress(recipients[i]); } // create message mimeMessage = new MimeMessage(session); mimeMessage.setSender(from); mimeMessage.setFrom(from); mimeMessage.setReplyTo(new Address[] { from }); mimeMessage.setRecipients(Message.RecipientType.TO, to); mimeMessage.setSubject(subject); mimeMessage.setText(message, "utf-8"); // send it Transport.send(mimeMessage); } catch (MessagingException ex) { LogFactory.getLog(GuestController.class).error("Unable to send email", ex); return false; } return true; }
From source file:edu.harvard.iq.dataverse.MailServiceBean.java
public boolean sendSystemEmail(String to, String subject, String messageText) { boolean sent = false; String rootDataverseName = dataverseService.findRootDataverse().getName(); String body = messageText + BundleUtil.getStringFromBundle("notification.email.closing", Arrays.asList(BrandingUtil.getInstallationBrandName(rootDataverseName))); logger.fine("Sending email to " + to + ". Subject: <<<" + subject + ">>>. Body: " + body); try {/*from ww w . j a v a 2s .co m*/ MimeMessage msg = new MimeMessage(session); InternetAddress systemAddress = getSystemAddress(); if (systemAddress != null) { msg.setFrom(systemAddress); msg.setSentDate(new Date()); String[] recipientStrings = to.split(","); InternetAddress[] recipients = new InternetAddress[recipientStrings.length]; for (int i = 0; i < recipients.length; i++) { try { recipients[i] = new InternetAddress('"' + recipientStrings[i] + '"', "", charset); } catch (UnsupportedEncodingException ex) { logger.severe(ex.getMessage()); } } msg.setRecipients(Message.RecipientType.TO, recipients); msg.setSubject(subject, charset); msg.setText(body, charset); try { Transport.send(msg, recipients); sent = true; } catch (SMTPSendFailedException ssfe) { logger.warning("Failed to send mail to " + to + " (SMTPSendFailedException)"); } } else { logger.fine("Skipping sending mail to " + to + ", because the \"no-reply\" address not set (" + Key.SystemEmail + " setting)."); } } catch (AddressException ae) { logger.warning("Failed to send mail to " + to); ae.printStackTrace(System.out); } catch (MessagingException me) { logger.warning("Failed to send mail to " + to); me.printStackTrace(System.out); } return sent; }