List of usage examples for javax.mail.internet MimeMessage setContent
@Override public void setContent(Multipart mp) throws MessagingException
From source file:org.protocoderrunner.apprunner.api.PNetwork.java
@ProtocoderScript @APIMethod(description = "Send an E-mail. It requires passing a EmailConf object", example = "") @APIParam(params = { "url", "function(data)" }) public void sendEmail(String from, String to, String subject, String text, final EmailConf emailSettings) throws AddressException, MessagingException { if (emailSettings == null) { return;// ww w .j a v a2 s.c o m } // final String host = "smtp.gmail.com"; // final String address = "@gmail.com"; // final String pass = ""; Multipart multiPart; String finalString = ""; Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable", emailSettings.ttl); props.put("mail.smtp.host", emailSettings.host); props.put("mail.smtp.user", emailSettings.user); props.put("mail.smtp.password", emailSettings.password); props.put("mail.smtp.port", emailSettings.port); props.put("mail.smtp.auth", emailSettings.auth); Log.i("Check", "done pops"); final Session session = Session.getDefaultInstance(props, null); DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain")); final MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setDataHandler(handler); Log.i("Check", "done sessions"); multiPart = new MimeMultipart(); InternetAddress toAddress; toAddress = new InternetAddress(to); message.addRecipient(Message.RecipientType.TO, toAddress); Log.i("Check", "added recipient"); message.setSubject(subject); message.setContent(multiPart); message.setText(text); Thread t = new Thread(new Runnable() { @Override public void run() { try { MLog.i("check", "transport"); Transport transport = session.getTransport("smtp"); MLog.i("check", "connecting"); transport.connect(emailSettings.host, emailSettings.user, emailSettings.password); MLog.i("check", "wana send"); transport.sendMessage(message, message.getAllRecipients()); transport.close(); MLog.i("check", "sent"); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } }); t.start(); }
From source file:userInterface.EnergySourceBoardSupervisor.ManageEnergyConsumptionsJPanel.java
public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) { String host = "smtp.gmail.com"; message = "Some of the appliances in your house are running inefficient." + "\n" + "Kindly check or replace your appliance " + "\n" + "Check the attachment for details or visit your account"; Properties props = System.getProperties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", 587); props.put("mail.smtp.user", from); Session session = Session.getDefaultInstance(props); MimeMessage mimeMessage = new MimeMessage(session); try {/*from w ww .j ava 2 s . c om*/ mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); mimeMessage.setSubject("Alert from Energy Board"); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(message); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(path); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(name_attach.getText() + ".png"); multipart.addBodyPart(messageBodyPart); mimeMessage.setContent(multipart); SMTPTransport transport = (SMTPTransport) session.getTransport("smtps"); transport.connect(host, from, password); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); System.out.println("sent"); transport.close(); } catch (MessagingException me) { } }
From source file:org.igov.io.mail.Mail.java
public void sendOld() throws EmailException { LOG.info("init"); try {//from ww w . ja v a 2s .c om MultiPartEmail oMultiPartEmail = new MultiPartEmail(); LOG.info("(getHost()={})", getHost()); oMultiPartEmail.setHostName(getHost()); String[] asTo = { sMailOnly(getTo()) }; if (getTo().contains("\\,")) { asTo = getTo().split("\\,");//sTo for (String s : asTo) { LOG.info("oMultiPartEmail.addTo (s={})", s); oMultiPartEmail.addTo(s, "receiver"); } } LOG.info("(getFrom()={})", getFrom()); LOG_BIG.debug("(getFrom()={})", getFrom()); oMultiPartEmail.setFrom(getFrom(), getFrom());//"iGov" oMultiPartEmail.setSubject(getHead()); LOG.info("getHead()={}", getHead()); String sLogin = getAuthUser(); if (sLogin != null && !"".equals(sLogin.trim())) { oMultiPartEmail.setAuthentication(sLogin, getAuthPassword()); LOG.info("withAuth"); } else { LOG.info("withoutAuth"); } //oMultiPartEmail.setAuthentication(getAuthUser(), getAuthPassword()); LOG.info("(getAuthUser()={})", getAuthUser()); //LOG.info("getAuthPassword()=" + getAuthPassword()); oMultiPartEmail.setSmtpPort(getPort()); LOG.info("(getPort()={})", getPort()); oMultiPartEmail.setSSL(isSSL()); LOG.info("(isSSL()={})", isSSL()); oMultiPartEmail.setTLS(isTLS()); LOG.info("(isTLS()={})", isTLS()); oSession = oMultiPartEmail.getMailSession(); MimeMessage oMimeMessage = new MimeMessage(oSession); //oMimeMessage.setFrom(new InternetAddress(getFrom(), "iGov", DEFAULT_ENCODING)); oMimeMessage.setFrom(new InternetAddress(getFrom(), getFrom())); //oMimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(sTo, sToName, DEFAULT_ENCODING)); String sReceiverName = "receiver"; if (asTo.length == 1) { sReceiverName = getToName(); } for (String s : asTo) { LOG.info("oMimeMessage.addRecipient (s={})", s); //oMultiPartEmail.addTo(s, "receiver"); oMimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(s, sReceiverName, DEFAULT_ENCODING)); } //oMimeMessage.addRecipient(Message.RecipientType.TO, // new InternetAddress(sTo, "recipient", DEFAULT_ENCODING)); //new InternetAddress(getTo(), "recipient", DEFAULT_ENCODING)); oMimeMessage.setSubject(getHead(), DEFAULT_ENCODING); _AttachBody(getBody()); //LOG.info("(getBody()={})", getBody()); oMimeMessage.setContent(oMultiparts); // oMimeMessage.getRecipients(Message.RecipientType.CC); //methodCallRunner.registrateMethod(Transport.class.getName(), "send", new Object[]{oMimeMessage}); Transport.send(oMimeMessage); LOG.info("Send " + getTo() + "!!!!!!!!!!!!!!!!!!!!!!!!"); } catch (Exception oException) { LOG.error("FAIL: {} (getTo()={})", oException.getMessage(), getTo()); LOG.trace("FAIL:", oException); throw new EmailException("Error happened when sending email (" + getTo() + ")" + "Exception message: " + oException.getMessage(), oException); } LOG.info("SUCCESS: Sent!"); }
From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java
/** * Creates a MIME message (message with binary content carrying capabilities) from an existing Mail * /*from w w w . ja v a2 s .c o m*/ * @param mail The original Mail object * @param session Mail session * @return The MIME message */ private MimeMessage createMimeMessage(Mail mail, Session session, XWikiContext context) throws MessagingException, XWikiException, IOException { // this will also check for email error InternetAddress from = new InternetAddress(mail.getFrom()); String recipients = mail.getHeader("To"); if (StringUtils.isBlank(recipients)) { recipients = mail.getTo(); } else { recipients = mail.getTo() + "," + recipients; } InternetAddress[] to = toInternetAddresses(recipients); recipients = mail.getHeader("Cc"); if (StringUtils.isBlank(recipients)) { recipients = mail.getCc(); } else { recipients = mail.getCc() + "," + recipients; } InternetAddress[] cc = toInternetAddresses(recipients); recipients = mail.getHeader("Bcc"); if (StringUtils.isBlank(recipients)) { recipients = mail.getBcc(); } else { recipients = mail.getBcc() + "," + recipients; } InternetAddress[] bcc = toInternetAddresses(recipients); if ((to == null) && (cc == null) && (bcc == null)) { LOGGER.info("No recipient -> skipping this email"); return null; } MimeMessage message = new MimeMessage(session); message.setSentDate(new Date()); message.setFrom(from); if (to != null) { message.setRecipients(javax.mail.Message.RecipientType.TO, to); } if (cc != null) { message.setRecipients(javax.mail.Message.RecipientType.CC, cc); } if (bcc != null) { message.setRecipients(javax.mail.Message.RecipientType.BCC, bcc); } message.setSubject(mail.getSubject(), EMAIL_ENCODING); for (Map.Entry<String, String> header : mail.getHeaders().entrySet()) { message.setHeader(header.getKey(), header.getValue()); } if (mail.getHtmlPart() != null || mail.getAttachments() != null) { Multipart multipart = createMimeMultipart(mail, context); message.setContent(multipart); } else { message.setText(mail.getTextPart()); } message.setSentDate(new Date()); message.saveChanges(); return message; }
From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java
/** * Send EmailEntry to smtp server//from w w w . j av a2 s.c o m * * @param email email to send * @throws NameNotFoundException if recipient cannot be found in LDAP server * @throws DataServiceException if LDAP server is not available * @throws MessagingException if some field of email cannot be encoded (malformed email address) */ private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException { final Properties props = System.getProperties(); props.put("mail.smtp.host", this.emailFactory.getSmtpHost()); props.put("mail.protocol.port", this.emailFactory.getSmtpPort()); final Session session = Session.getInstance(props, null); final MimeMessage message = new MimeMessage(session); Account recipient = this.accountDao.findByUID(email.getRecipient()); InternetAddress[] senders = { new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) }; message.addFrom(senders); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail())); message.setSubject(email.getSubject()); message.setHeader("Date", (new MailDateFormat()).format(email.getDate())); // Mail content Multipart multiPart = new MimeMultipart("alternative"); // attachments for (Attachment att : email.getAttachments()) { MimeBodyPart mbp = new MimeBodyPart(); mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType()))); mbp.setFileName(att.getName()); multiPart.addBodyPart(mbp); } // html part MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(email.getBody(), "text/html; charset=utf-8"); multiPart.addBodyPart(htmlPart); message.setContent(multiPart); // Send message Transport.send(message); }
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;/*from w w w.ja v a2 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:org.georchestra.console.ws.emails.EmailController.java
/** * Send EmailEntry to smtp server//from w w w .j a v a2s. c om * * @param email email to send * @throws NameNotFoundException if recipient cannot be found in LDAP server * @throws DataServiceException if LDAP server is not available * @throws MessagingException if some field of email cannot be encoded (malformed email address) */ private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException { final Session session = Session.getInstance(System.getProperties(), null); session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost()); session.getProperties().setProperty("mail.smtp.port", (new Integer(this.emailFactory.getSmtpPort())).toString()); final MimeMessage message = new MimeMessage(session); Account recipient = this.accountDao.findByUID(email.getRecipient()); InternetAddress[] senders = { new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) }; message.addFrom(senders); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail())); message.setSubject(email.getSubject()); message.setHeader("Date", (new MailDateFormat()).format(email.getDate())); // Mail content Multipart multiPart = new MimeMultipart("alternative"); // attachments for (Attachment att : email.getAttachments()) { MimeBodyPart mbp = new MimeBodyPart(); mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType()))); mbp.setFileName(att.getName()); multiPart.addBodyPart(mbp); } // html part MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(email.getBody(), "text/html; charset=utf-8"); multiPart.addBodyPart(htmlPart); message.setContent(multiPart); // Send message Transport.send(message); }
From source file:org.sakaiproject.kernel.messaging.email.EmailMessageListener.java
public void handleMessage(Message email) throws AddressException, UnsupportedEncodingException, SendFailedException, MessagingException, IOException { String fromAddress = email.getHeader(Message.Field.FROM); if (fromAddress == null) { throw new MessagingException("Unable to send without a 'from' address."); }//from w w w . ja va2s . c om // transform to a MimeMessage ArrayList<String> invalids = new ArrayList<String>(); // convert and validate the 'from' address InternetAddress from = new InternetAddress(fromAddress, true); // convert and validate reply to addresses String replyTos = email.getHeader(EmailMessage.Field.REPLY_TO); InternetAddress[] replyTo = emails2Internets(replyTos, invalids); // convert and validate the 'to' addresses String tos = email.getHeader(Message.Field.TO); InternetAddress[] to = emails2Internets(tos, invalids); // convert and validate 'cc' addresses String ccs = email.getHeader(EmailMessage.Field.CC); InternetAddress[] cc = emails2Internets(ccs, invalids); // convert and validate 'bcc' addresses String bccs = email.getHeader(EmailMessage.Field.BCC); InternetAddress[] bcc = emails2Internets(bccs, invalids); int totalRcpts = to.length + cc.length + bcc.length; if (totalRcpts == 0) { throw new MessagingException("No recipients to send to."); } MimeMessage mimeMsg = new MimeMessage(session); mimeMsg.setFrom(from); mimeMsg.setReplyTo(replyTo); mimeMsg.setRecipients(RecipientType.TO, to); mimeMsg.setRecipients(RecipientType.CC, cc); mimeMsg.setRecipients(RecipientType.BCC, bcc); // add in any additional headers Map<String, String> headers = email.getHeaders(); if (headers != null && !headers.isEmpty()) { for (Entry<String, String> header : headers.entrySet()) { mimeMsg.setHeader(header.getKey(), header.getValue()); } } // add the content to the message List<Message> parts = email.getParts(); if (parts == null || parts.size() == 0) { setContent(mimeMsg, email); } else { // create a multipart container Multipart multipart = new MimeMultipart(); // create a body part for the message text MimeBodyPart msgBodyPart = new MimeBodyPart(); setContent(msgBodyPart, email); // add the message part to the container multipart.addBodyPart(msgBodyPart); // add attachments for (Message part : parts) { addPart(multipart, part); } // set the multipart container as the content of the message mimeMsg.setContent(multipart); } if (allowTransport) { // send Transport.send(mimeMsg); } else { try { ByteArrayOutputStream output = new ByteArrayOutputStream(); mimeMsg.writeTo(output); String emailString = output.toString(); LOG.info(emailString); observable.notifyObservers(emailString); } catch (IOException e) { LOG.info("Transport disabled and unable to write message to log: " + e.getMessage(), e); } } }
From source file:com.gtwm.jasperexecute.RunJasperReports.java
public void emailReport(String emailHost, String emailUser, String emailPass, Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames) throws MessagingException { Properties props = new Properties(); //props.setProperty("mail.debug", "true"); props.setProperty("mail.smtp.host", emailHost); if (emailUser != null) { props.setProperty("mail.smtp.auth", "true"); }/* ww w. ja v a2 s .c o m*/ Authenticator emailAuthenticator = new EmailAuthenticator(emailUser, emailPass); Session mailSession = Session.getDefaultInstance(props, emailAuthenticator); MimeMessage message = new MimeMessage(mailSession); message.setSubject(emailSubject); for (String emailRecipient : emailRecipients) { Address toAddress = new InternetAddress(emailRecipient); message.addRecipient(Message.RecipientType.TO, toAddress); } Address fromAddress = new InternetAddress(emailSender); message.setFrom(fromAddress); // Message text Multipart multipart = new MimeMultipart(); BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText("Database report attached\n\n"); multipart.addBodyPart(textBodyPart); // Attachments for (String attachmentFileName : attachmentFileNames) { BodyPart attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachmentFileName); attachmentBodyPart.setDataHandler(new DataHandler(source)); String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", ""); fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", ""); attachmentBodyPart.setFileName(fileNameWithoutPath); multipart.addBodyPart(attachmentBodyPart); } // add parts to message message.setContent(multipart); // send via SMTP Transport transport = mailSession.getTransport("smtp"); // transport.connect(emailHost, emailUser, emailPass); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); }
From source file:org.pentaho.platform.util.Emailer.java
public boolean send() { String from = props.getProperty("mail.from.default"); String fromName = props.getProperty("mail.from.name"); String to = props.getProperty("to"); String cc = props.getProperty("cc"); String bcc = props.getProperty("bcc"); boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth")); String subject = props.getProperty("subject"); String body = props.getProperty("body"); logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject + "' and the body " + body); try {/*w ww .ja va 2 s . c o m*/ // Get a Session object Session session; if (authenticate) { session = Session.getInstance(props, authenticator); } else { session = Session.getInstance(props); } // if debugging is not set in the email config file, then default to false if (!props.containsKey("mail.debug")) { //$NON-NLS-1$ session.setDebug(false); } final MimeMessage msg; if (EMBEDDED_HTML.equals(attachmentMimeType)) { //Message is ready msg = new MimeMessage(session, attachment); if (body != null) { //We need to add message to the top of the email body final MimeMultipart oldMultipart = (MimeMultipart) msg.getContent(); final MimeMultipart newMultipart = new MimeMultipart("related"); for (int i = 0; i < oldMultipart.getCount(); i++) { BodyPart bodyPart = oldMultipart.getBodyPart(i); final Object content = bodyPart.getContent(); //Main HTML body if (content instanceof String) { final String newContent = body + "<br/><br/>" + content; final MimeBodyPart part = new MimeBodyPart(); part.setText(newContent, "UTF-8", "html"); newMultipart.addBodyPart(part); } else { //CID attachments newMultipart.addBodyPart(bodyPart); } } msg.setContent(newMultipart); } } else { // construct the message msg = new MimeMessage(session); Multipart multipart = new MimeMultipart(); if (attachment == null) { logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$ return false; } ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType); if (body != null) { MimeBodyPart bodyMessagePart = new MimeBodyPart(); bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding()); multipart.addBodyPart(bodyMessagePart); } // attach the file to the message MimeBodyPart attachmentBodyPart = new MimeBodyPart(); attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null)); multipart.addBodyPart(attachmentBodyPart); // add the Multipart to the message msg.setContent(multipart); } if (from != null) { msg.setFrom(new InternetAddress(from, fromName)); } else { // There should be no way to get here logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$ } if ((to != null) && (to.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); } if ((cc != null) && (cc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); } if ((bcc != null) && (bcc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); } if (subject != null) { msg.setSubject(subject, LocaleHelper.getSystemEncoding()); } msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); return true; } catch (SendFailedException e) { logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$ } catch (AuthenticationFailedException e) { logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$ } catch (Throwable e) { logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$ } return false; }