List of usage examples for javax.mail Message setFrom
public abstract void setFrom(Address address) throws MessagingException;
From source file:transport.java
public void go(Session session, InternetAddress[] toAddr, InternetAddress from) { Transport trans = null;//from w w w.j a v a2 s.c o m try { // create a message Message msg = new MimeMessage(session); msg.setFrom(from); msg.setRecipients(Message.RecipientType.TO, toAddr); msg.setSubject("JavaMail APIs transport.java Test"); msg.setSentDate(new Date()); // Date: header msg.setContent(msgText + msgText2, "text/plain"); msg.saveChanges(); // get the smtp transport for the address trans = session.getTransport(toAddr[0]); // register ourselves as listener for ConnectionEvents // and TransportEvents trans.addConnectionListener(this); trans.addTransportListener(this); // connect the transport trans.connect(); // send the message trans.sendMessage(msg, toAddr); // give the EventQueue enough time to fire its events try { Thread.sleep(5); } catch (InterruptedException e) { } } catch (MessagingException mex) { // give the EventQueue enough time to fire its events try { Thread.sleep(5); } catch (InterruptedException e) { } System.out.println("Sending failed with exception:"); mex.printStackTrace(); System.out.println(); Exception ex = mex; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { System.out.println(" ** Invalid Addresses"); for (int i = 0; i < invalid.length; i++) System.out.println(" " + invalid[i]); } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { System.out.println(" ** ValidUnsent Addresses"); for (int i = 0; i < validUnsent.length; i++) System.out.println(" " + validUnsent[i]); } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { System.out.println(" ** ValidSent Addresses"); for (int i = 0; i < validSent.length; i++) System.out.println(" " + validSent[i]); } } System.out.println(); if (ex instanceof MessagingException) ex = ((MessagingException) ex).getNextException(); else ex = null; } while (ex != null); } finally { try { // close the transport if (trans != null) trans.close(); } catch (MessagingException mex) { /* ignore */ } } }
From source file:com.sfs.ucm.service.MailService.java
/** * Send mail message in plain text. Mail host is obtained from instance-specific properties file via AppManager. * /*from ww w. j a v a2s. co m*/ * @param fromAddress * @param ccRe * @param toRecipient * @param subject * @param body * @param messageType * - text/plain or text/html * @return status message * @throws IllegalArgumentException */ @Asynchronous public Future<String> sendMessage(final String fromAddress, final String ccRecipient, final String toRecipient, final String subject, final String body, final String messageType) throws IllegalArgumentException { // argument validation if (fromAddress == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined fromAddress"); } if (toRecipient == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined toRecipient"); } if (subject == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined subject"); } if (body == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined body conent"); } if (messageType == null || (!messageType.equals("text/plain") && !messageType.equals("text/html"))) { throw new IllegalArgumentException("sendMessage: Invalid or undefined messageType"); } String status = null; try { Properties props = new Properties(); props.put("mail.smtp.host", appManager.getApplicationProperty("mail.host")); props.put("mail.smtp.port", appManager.getApplicationProperty("mail.port")); Object[] params = new Object[4]; params[0] = (String) subject; params[1] = (String) fromAddress; params[2] = (String) ccRecipient; params[3] = (String) toRecipient; logger.info("Sending message: subject: {}, fromAddress: {}, ccRecipient: {}, toRecipient: {}", params); Session session = Session.getDefaultInstance(props); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromAddress)); Address toAddress = new InternetAddress(toRecipient); message.addRecipient(Message.RecipientType.TO, toAddress); if (StringUtils.isNotBlank(ccRecipient)) { Address ccAddress = new InternetAddress(ccRecipient); message.addRecipient(Message.RecipientType.CC, ccAddress); } message.setSubject(subject); message.setContent(body, messageType); Transport.send(message); } catch (AddressException e) { logger.error("sendMessage Address Exception occurred: {}", e.getMessage()); status = "sendMessage Address Exception occurred"; } catch (MessagingException e) { logger.error("sendMessage Messaging Exception occurred: {}", e.getMessage()); status = "sendMessage Messaging Exception occurred"; } return new AsyncResult<String>(status); }
From source file:com.sfs.ucm.service.MailService.java
/** * Send mail message in plain text. Mail host is obtained from instance-specific properties file via AppManager. * //from w w w . j a v a 2 s . c o m * @param fromAddress * @param recipients * - fully qualified recipient address * @param subject * @param body * @param messageType * - text/plain or text/html * @throws IllegalArgumentException */ @Asynchronous public Future<String> sendMessage(final String fromAddress, final String ccRecipient, final String[] toRecipients, final String subject, final String body, final String messageType) { // argument validation if (fromAddress == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined fromAddress"); } if (toRecipients == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined toRecipients"); } if (subject == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined subject"); } if (body == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined body conent"); } if (messageType == null || (!messageType.equals("text/plain") && !messageType.equals("text/html"))) { throw new IllegalArgumentException("sendMessage: Invalid or undefined messageType"); } String status = null; try { Properties props = new Properties(); props.put("mail.smtp.host", appManager.getApplicationProperty("mail.host")); props.put("mail.smtp.port", appManager.getApplicationProperty("mail.port")); Object[] params = new Object[4]; params[0] = (String) subject; params[1] = (String) fromAddress; params[2] = (String) ccRecipient; params[3] = (String) StringUtils.join(toRecipients); logger.info("Sending message: subject: {}, fromAddress: {}, ccRecipient: {}, toRecipient: {}", params); Session session = Session.getDefaultInstance(props); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromAddress)); Address[] toAddresses = new Address[toRecipients.length]; for (int i = 0; i < toAddresses.length; i++) { toAddresses[i] = new InternetAddress(toRecipients[i]); } message.addRecipients(Message.RecipientType.TO, toAddresses); if (StringUtils.isNotBlank(ccRecipient)) { Address ccAddress = new InternetAddress(ccRecipient); message.addRecipient(Message.RecipientType.CC, ccAddress); } message.setSubject(subject); message.setContent(body, messageType); Transport.send(message); } catch (AddressException e) { logger.error("sendMessage Address Exception occurred: {}", e.getMessage()); status = "sendMessage Address Exception occurred"; } catch (MessagingException e) { logger.error("sendMessage Messaging Exception occurred: {}", e.getMessage()); status = "sendMessage Messaging Exception occurred"; } return new AsyncResult<String>(status); }
From source file:transport.java
public void go(Session session, InternetAddress[] toAddr, InternetAddress from) { Transport trans = null;//from w w w .j av a 2 s .c o m try { // create a message Message msg = new MimeMessage(session); msg.setFrom(from); msg.setRecipients(Message.RecipientType.TO, toAddr); msg.setSubject("JavaMail APIs transport.java Test"); msg.setSentDate(new Date()); // Date: header msg.setContent(msgText + msgText2, "text/plain"); msg.saveChanges(); // get the smtp transport for the address trans = session.getTransport(toAddr[0]); // register ourselves as listener for ConnectionEvents // and TransportEvents trans.addConnectionListener(this); trans.addTransportListener(this); // connect the transport trans.connect(); // send the message trans.sendMessage(msg, toAddr); // give the EventQueue enough time to fire its events try { Thread.sleep(5); } catch (InterruptedException e) { } } catch (MessagingException mex) { // give the EventQueue enough time to fire its events try { Thread.sleep(5); } catch (InterruptedException e) { } mex.printStackTrace(); System.out.println(); Exception ex = mex; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { System.out.println(" ** Invalid Addresses"); if (invalid != null) { for (int i = 0; i < invalid.length; i++) System.out.println(" " + invalid[i]); } } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { System.out.println(" ** ValidUnsent Addresses"); if (validUnsent != null) { for (int i = 0; i < validUnsent.length; i++) System.out.println(" " + validUnsent[i]); } } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { System.out.println(" ** ValidSent Addresses"); if (validSent != null) { for (int i = 0; i < validSent.length; i++) System.out.println(" " + validSent[i]); } } } System.out.println(); if (ex instanceof MessagingException) ex = ((MessagingException) ex).getNextException(); else ex = null; } while (ex != null); } finally { try { // close the transport trans.close(); } catch (MessagingException mex) { /* ignore */ } } }
From source file:org.infoglue.common.util.mail.MailService.java
/** * *//*from ww w .j ava 2 s .com*/ private Message createMessage(String from, String to, String subject, String content) throws SystemException { try { final Message message = new MimeMessage(this.session); message.setContent(content, "text/html"); message.setFrom(createInternetAddress(from)); message.setRecipient(Message.RecipientType.TO, createInternetAddress(to)); message.setSubject(subject); message.setText(content); message.setDataHandler(new DataHandler(new StringDataSource(content, "text/html"))); return message; } catch (MessagingException e) { throw new SystemException("Unable to create the message.", e); } }
From source file:eagle.common.email.EagleMailClient.java
private boolean _send(String from, String to, String cc, String title, String content) { Message msg = new MimeMessage(session); try {//from w w w .ja v a 2s .c o m msg.setFrom(new InternetAddress(from)); msg.setSubject(title); if (to != null) { msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); } if (cc != null) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc)); } //msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(DEFAULT_BCC_ADDRESS)); msg.setContent(content, "text/html;charset=utf-8"); LOG.info(String.format("Going to send mail: from[%s], to[%s], cc[%s], title[%s]", from, to, cc, title)); Transport.send(msg); return true; } catch (AddressException e) { LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e); return false; } catch (MessagingException e) { LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e); return false; } }
From source file:it.infn.ct.security.utilities.LDAPCleaner.java
private void sendUserRemainder(UserRequest ur, int days) { javax.mail.Session session = null;/*from w w w . j av a 2 s . c om*/ try { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); session = (javax.mail.Session) envCtx.lookup("mail/Users"); Message mailMsg = new MimeMessage(session); mailMsg.setFrom(new InternetAddress(rb.getString("mailSender"), rb.getString("IdPAdmin"))); InternetAddress mailTo[] = new InternetAddress[1]; mailTo[0] = new InternetAddress(getGoodMail(ur), ur.getTitle() + " " + ur.getGivenname() + " " + ur.getSurname()); mailMsg.setRecipients(Message.RecipientType.TO, mailTo); if (rb.containsKey("mailCopy") && !rb.getString("mailCopy").isEmpty()) { String ccMail[] = rb.getString("mailCopy").split(";"); InternetAddress mailCCopy[] = new InternetAddress[ccMail.length]; for (int i = 0; i < ccMail.length; i++) { mailCCopy[i] = new InternetAddress(ccMail[i]); } mailMsg.setRecipients(Message.RecipientType.CC, mailCCopy); } if (days > 0) { mailMsg.setSubject( rb.getString("mailNotificationSubject").replace("_DAYS_", Integer.toString(days))); mailMsg.setText(rb.getString("mailNotificationBody") .replaceAll("_USER_", ur.getTitle() + " " + ur.getGivenname() + " " + ur.getSurname()) .replace("_DAYS_", Integer.toString(days))); } else { mailMsg.setSubject(rb.getString("mailDeleteSubject").replace("_DAYS_", Integer.toString(days))); mailMsg.setText(rb.getString("mailDeleteBody") .replaceAll("_USER_", ur.getTitle() + " " + ur.getGivenname() + " " + ur.getSurname()) .replace("_DAYS_", Integer.toString(days))); } Transport.send(mailMsg); } catch (Exception ex) { _log.error("Mail resource lookup error"); _log.error(ex.getMessage()); } }
From source file:it.infn.ct.security.actions.PassRecovery.java
private void sendMail(String code) throws MailException { javax.mail.Session session = null;//from w w w . j av a 2s.com try { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); session = (javax.mail.Session) envCtx.lookup("mail/Users"); } catch (Exception ex) { _log.error("Mail resource lookup error"); _log.error(ex.getMessage()); throw new MailException("Mail Resource not available"); } Message mailMsg = new MimeMessage(session); try { String title = user.getTitle() == null ? "" : user.getTitle(); mailMsg.setFrom(new InternetAddress(mailFrom)); InternetAddress mailTo[] = new InternetAddress[1]; mailTo[0] = new InternetAddress(user.getPreferredMail(), title + user.getGivenname() + " " + user.getSurname()); mailMsg.setRecipients(Message.RecipientType.TO, mailTo); mailMsg.setSubject(mailSubject); mailBody = mailBody.replaceAll("_USER_", title + " " + user.getGivenname() + " " + user.getSurname()); mailBody = mailBody.replaceAll("_CODE_", code); mailMsg.setText(mailBody); Transport.send(mailMsg); } catch (UnsupportedEncodingException ex) { _log.error(ex); throw new MailException("Mail from address format not valid"); } catch (MessagingException ex) { _log.error(ex); throw new MailException("Mail message has problems"); } }
From source file:com.meg7.emailer.EmailerManager.java
private Message createMessage(List<String> emails, String fromEmail, String fromName, String subject, String text, Session session) throws MessagingException, UnsupportedEncodingException { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromEmail, fromName)); for (String email : emails) { message.addRecipient(Message.RecipientType.BCC, new InternetAddress(email, email)); }/*from w ww . ja v a2 s .com*/ message.setSubject(subject); message.setText(text); return message; }
From source file:pt.ist.fenixedu.integration.task.exportData.parking.ExportCarParkUsers.java
private void sendParkingInfoToRemoteCarPark(String filename, byte[] byteArray) throws AddressException, MessagingException { final Properties properties = new Properties(); properties.put("mail.smtp.host", FenixEduAcademicConfiguration.getConfiguration().getMailSmtpHost()); properties.put("mail.smtp.name", FenixEduAcademicConfiguration.getConfiguration().getMailSmtpName()); properties.put("mailSender.max.recipients", FenixEduAcademicConfiguration.getConfiguration().getMailSenderMaxRecipients()); properties.put("mail.debug", "false"); final Session session = Session.getDefaultInstance(properties, null); final Sender sender = Bennu.getInstance().getSystemSender(); final Message message = new MimeMessage(session); message.setFrom(new InternetAddress(sender.getFromAddress())); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(EMAIL_ADDRESSES_TO_SEND_DATA)); message.setSubject("Utentes IST - Atualizao"); message.setText("Listagem atualizada de utentes do IST: " + new DateTime().toString("yyyy-MM-dd HH:mm")); MimeBodyPart messageBodyPart = new MimeBodyPart(); Multipart multipart = new MimeMultipart(); messageBodyPart = new MimeBodyPart(); DataSource source = new ByteArrayDataSource(byteArray, "text/plain"); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); message.setContent(multipart);//from ww w . j a va 2 s . c o m Transport.send(message); }