List of usage examples for javax.mail.internet MimeMessage setFrom
public void setFrom(String address) throws MessagingException
From source file:ee.cyber.licensing.service.MailService.java
public void sendExpirationNearingMail(License license) throws IOException, MessagingException { logger.info("1st ===> setup Mail Server Properties"); Properties mailServerProperties = getProperties(); final String email = mailServerProperties.getProperty("fromEmail"); final String password = mailServerProperties.getProperty("password"); final String host = mailServerProperties.getProperty("mail.smtp.host"); final String mailTo = mailServerProperties.getProperty("mailTo"); logger.info("2nd ===> create Authenticator object to pass in Session.getInstance argument"); Authenticator authentication = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(email, password); }/*w w w .j ava2 s . c o m*/ }; logger.info("Mail Server Properties have been setup successfully"); logger.info("3rd ===> get Mail Session.."); Session getMailSession = Session.getInstance(mailServerProperties, authentication); logger.info("4th ===> generateAndSendEmail() starts"); MimeMessage mailMessage = new MimeMessage(getMailSession); mailMessage.addHeader("Content-type", "text/html; charset=UTF-8"); mailMessage.addHeader("format", "flowed"); mailMessage.addHeader("Content-Transfer-Encoding", "8bit"); mailMessage.setFrom(new InternetAddress(email, "Licensing service")); mailMessage.setSubject("License with id " + license.getId() + " is expiring"); mailMessage.setSentDate(new Date()); mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo)); String emailBody = "This is test<br><br> Regards, <br>Licensing team"; mailMessage.setContent(emailBody, "text/html"); logger.info("5th ===> Get Session"); sendMail(email, password, host, getMailSession, mailMessage); }
From source file:org.exoplatform.extension.social.notifications.SocialNotificationService.java
/** * //from www. j a v a2s .co m * @param space * @param managers * @param pendingUsers */ private void pendingUserNotification(Space space, List<Profile> managerList, List<Profile> pendingUsers) { //TODO : use groovy template stored in JCR for mail information (cleaner, real templating) log.info("Sending mail to space manager : pending users"); try { // loop on each manager and send mail // like that each manager will have the mail in its preferred language // ideally should be done in a different executor // TODO: see if we can optimize this to avoid do it for all user // - send a mail to all the users in the same time (what about language) // - cache the template result and send mail for (Profile manager : managerList) { Locale locale = Locale.getDefault(); // get default locale of the manager String userId = manager.getIdentity().getRemoteId(); String userLocale = this.getOrganizationService().getUserProfileHandler() .findUserProfileByName(userId).getAttribute("user.language"); if (userLocale != null && !userLocale.trim().isEmpty()) { locale = new Locale(userLocale); } // getMessageTemplate MessageTemplate messageTemplate = this.getMailMessageTemplate( SocialNotificationConfiguration.MAIL_TEMPLATE_SPACE_PENDING_USERS, locale); GroovyTemplate g = new GroovyTemplate(messageTemplate.getSubject()); String spaceUrl = this.getPortalUrl() + "/portal/g/:spaces:" + space.getUrl() + "/" + space.getUrl() + "/settings"; //TODO: see which API to use String spaceAvatarUrl = null; if (space.getAvatarUrl() != null) { spaceAvatarUrl = this.getPortalUrl() + space.getAvatarUrl(); } Map binding = new HashMap(); binding.put("space", space); binding.put("portalUrl", this.getPortalUrl()); binding.put("spaceSettingUrl", spaceUrl); binding.put("spaceAvatarUrl", spaceAvatarUrl); binding.put("userPendingList", pendingUsers); String subject = g.render(binding); g = new GroovyTemplate(messageTemplate.getHtmlContent()); String htmlContent = g.render(binding); g = new GroovyTemplate(messageTemplate.getPlainTextContent()); String textContent = g.render(binding); MailService mailService = this.getMailService(); Session mailSession = mailService.getMailSession(); MimeMessage message = new MimeMessage(mailSession); message.setFrom(this.getSenderAddress()); // send email to manager message.setRecipient(RecipientType.TO, new InternetAddress(manager.getEmail(), manager.getFullName())); message.setSubject(subject); MimeMultipart content = new MimeMultipart("alternative"); MimeBodyPart text = new MimeBodyPart(); MimeBodyPart html = new MimeBodyPart(); text.setText(textContent); html.setContent(htmlContent, "text/html; charset=ISO-8859-1"); content.addBodyPart(text); content.addBodyPart(html); message.setContent(content); log.info("Sending mail to" + manager.getEmail() + " : " + subject + " : " + subject + "\n" + html); //mailService.sendMessage(message); } } catch (Exception ex) { ex.printStackTrace(); } }
From source file:com.cosmicpush.plugins.smtp.EmailMessage.java
/** * @param session the applications current session. * @throws EmailMessageException in response to any other type of exception. */// w ww . j ava 2 s . co m @SuppressWarnings({ "ConstantConditions" }) protected void send(Session session) throws EmailMessageException { try { // create a message MimeMessage msg = new MimeMessage(session); //set some of the basic attributes. msg.setFrom(fromAddress); msg.setRecipients(Message.RecipientType.TO, ReflectUtils.toArray(InternetAddress.class, toAddresses)); msg.setSubject(subject); msg.setSentDate(new Date()); if (replyToAddress.isEmpty() == false) { msg.setReplyTo(ReflectUtils.toArray(InternetAddress.class, replyToAddress)); } // create the Multipart and add set it as the content of the message Multipart multipart = new MimeMultipart(); msg.setContent(multipart); // create and fill the HTML part of the messgae if it exists if (html != null) { MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(html, "UTF-8", "html"); multipart.addBodyPart(bodyPart); } // create and fill the text part of the messgae if it exists if (text != null) { MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(text, "UTF-8", "plain"); multipart.addBodyPart(bodyPart); } if (html == null && text == null) { MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText("", "UTF-8", "plain"); multipart.addBodyPart(bodyPart); } // remove any nulls from the list of attachments. while (attachments.remove(null)) { /* keep going */ } // Attach any files that we have, making sure that they exist first for (File file : attachments) { if (file.exists() == false) { throw new EmailMessageException("The file \"" + file.getAbsolutePath() + "\" does not exist."); } else { MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.attachFile(file); multipart.addBodyPart(attachmentPart); } } // send the message Transport.send(msg); } catch (EmailMessageException ex) { throw ex; } catch (Exception ex) { throw new EmailMessageException("Exception sending email\n" + toString(), ex); } }
From source file:fr.xebia.demo.amazon.aws.AmazonAwsIamAccountCreatorV2.java
/** * Send email with Amazon Simple Email Service. * <p/>//ww w.j ava 2 s . c om * * Please note that the sender (ie 'from') must be a verified address (see * {@link AmazonSimpleEmailService#verifyEmailAddress(com.amazonaws.services.simpleemail.model.VerifyEmailAddressRequest)} * ). * <p/> * * Please note that the sender is a CC of the meail to ease support. * <p/> * * @param subject * @param body * @param from * @param toAddresses * @throws MessagingException * @throws AddressException */ public void sendEmail(String subject, String body, AccessKey accessKey, KeyPair sshKeyPair, java.security.KeyPair x509KeyPair, X509Certificate x509Certificate, SigningCertificate signingCertificate, String from, String toAddress) { try { Session s = Session.getInstance(new Properties(), null); MimeMessage msg = new MimeMessage(s); msg.setFrom(new InternetAddress(from)); msg.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toAddress)); msg.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(from)); msg.setSubject(subject); MimeMultipart mimeMultiPart = new MimeMultipart(); msg.setContent(mimeMultiPart); // body BodyPart plainTextBodyPart = new MimeBodyPart(); mimeMultiPart.addBodyPart(plainTextBodyPart); plainTextBodyPart.setContent(body, "text/plain"); // aws-credentials.txt / accessKey { BodyPart awsCredentialsBodyPart = new MimeBodyPart(); awsCredentialsBodyPart.setFileName("aws-credentials.txt"); StringWriter awsCredentialsStringWriter = new StringWriter(); PrintWriter awsCredentials = new PrintWriter(awsCredentialsStringWriter); awsCredentials .println("#Insert your AWS Credentials from http://aws.amazon.com/security-credentials"); awsCredentials.println("#" + new DateTime()); awsCredentials.println(); awsCredentials.println("# ec2, rds & elb tools use accessKey and secretKey"); awsCredentials.println("accessKey=" + accessKey.getAccessKeyId()); awsCredentials.println("secretKey=" + accessKey.getSecretAccessKey()); awsCredentials.println(); awsCredentials.println("# iam tools use AWSAccessKeyId and AWSSecretKey"); awsCredentials.println("AWSAccessKeyId=" + accessKey.getAccessKeyId()); awsCredentials.println("AWSSecretKey=" + accessKey.getSecretAccessKey()); awsCredentialsBodyPart.setContent(awsCredentialsStringWriter.toString(), "text/plain"); mimeMultiPart.addBodyPart(awsCredentialsBodyPart); } // private ssh key { BodyPart keyPairBodyPart = new MimeBodyPart(); keyPairBodyPart.setFileName(sshKeyPair.getKeyName() + ".pem.txt"); keyPairBodyPart.setContent(sshKeyPair.getKeyMaterial(), "application/octet-stream"); mimeMultiPart.addBodyPart(keyPairBodyPart); } // x509 private key { BodyPart x509PrivateKeyBodyPart = new MimeBodyPart(); x509PrivateKeyBodyPart.setFileName("pk-" + signingCertificate.getCertificateId() + ".pem.txt"); String x509privateKeyPem = Pems.pem(x509KeyPair.getPrivate()); x509PrivateKeyBodyPart.setContent(x509privateKeyPem, "application/octet-stream"); mimeMultiPart.addBodyPart(x509PrivateKeyBodyPart); } // x509 private key { BodyPart x509CertificateBodyPart = new MimeBodyPart(); x509CertificateBodyPart.setFileName("cert-" + signingCertificate.getCertificateId() + ".pem.txt"); String x509CertificatePem = Pems.pem(x509Certificate); x509CertificateBodyPart.setContent(x509CertificatePem, "application/octet-stream"); mimeMultiPart.addBodyPart(x509CertificateBodyPart); } // Convert to raw message ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); RawMessage rawMessage = new RawMessage(); rawMessage.setData(ByteBuffer.wrap(out.toString().getBytes())); ses.sendRawEmail(new SendRawEmailRequest().withRawMessage(rawMessage)); } catch (Exception e) { throw Throwables.propagate(e); } }
From source file:org.pentaho.platform.scheduler2.email.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 {/*ww w . j a va2 s . co 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); } // construct the message MimeMessage msg = new MimeMessage(session); Multipart multipart = new MimeMultipart(); 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()); } 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); 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; }
From source file:org.bibsonomy.util.MailUtils.java
/** * Sends a mail to the given recipients/*from w w w .jav a2s. 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:com.smartitengineering.emailq.service.impl.EmailServiceImpl.java
protected void sendEmail(Email email, List<Email> successfulEmails) { try {//from w w w . ja v a 2 s . c om if (logger.isDebugEnabled()) { logger.debug("Attempting to send " + email.getId() + " " + email.getSubject()); if (email.getTo() != null) { logger.debug("To: " + Arrays.toString(email.getTo().toArray())); } else { logger.debug("To is NULL"); } if (email.getTo() != null) { logger.debug("CC: " + Arrays.toString(email.getCc().toArray())); } else { logger.debug("CC is NULL"); } if (email.getTo() != null) { logger.debug("BCC: " + Arrays.toString(email.getBcc().toArray())); } else { logger.debug("BCC is NULL"); } if (email.getTo() != null) { logger.debug("FROM: " + email.getFrom()); } else { logger.debug("FROM is NULL"); } if (email.getAttachments() != null) { logger.debug("Attachments: " + Arrays.toString(email.getAttachments().toArray())); for (Attachments attachment : email.getAttachments()) { logger.debug("Attachment: " + attachment.getName()); } } else { logger.debug("No attachments"); } } //Send email if (StringUtils.isBlank(email.getSubject()) || StringUtils.isBlank(email.getFrom())) { logger.warn(new StringBuilder("Invalid email without either from or a subject, thus ignoring it ") .append(email.getId()).toString()); return; } MimeMessage message = new MimeMessage(session); message.setSubject(email.getSubject()); message.setFrom(new InternetAddress(email.getFrom())); addRecipients(message, Message.RecipientType.TO, email.getTo()); addRecipients(message, Message.RecipientType.CC, email.getCc()); addRecipients(message, Message.RecipientType.BCC, email.getBcc()); if (email.getMessage() != null && StringUtils.isNotBlank(email.getMessage().getMsgBody()) && email.getMessage().getMsgType().equals(MsgType.PLAIN) && (email.getAttachments() == null || email.getAttachments().isEmpty())) { message.setText(email.getMessage().getMsgBody()); } else { Multipart multipart = new MimeMultipart(); if (email.getMessage() != null && StringUtils.isNotBlank(email.getMessage().getMsgBody())) { MimeBodyPart bodyPart = new MimeBodyPart(); switch (email.getMessage().getMsgType()) { case HTML: bodyPart.setContent(email.getMessage().getMsgBody(), "html"); break; case PLAIN: default: bodyPart.setText(email.getMessage().getMsgBody()); } multipart.addBodyPart(bodyPart); } if (email.getAttachments() != null && !email.getAttachments().isEmpty()) { for (Attachments attachment : email.getAttachments()) { addAttachment(multipart, attachment); } } message.setContent(multipart); } Transport.send(message); if (logger.isDebugEnabled()) { logger.debug("Sent " + email.getId()); } //Update status email.setMailStatus(Email.MailStatus.SENT); successfulEmails.add(email); if (logger.isDebugEnabled()) { logger.debug("Set new mail status and add to successful queue " + email.getSubject()); } } catch (Exception ex) { logger.warn( new StringBuilder("Error sending email with subject ").append(email.getSubject()).toString(), ex); } }
From source file:org.apache.hupa.server.handler.AbstractSendMessageHandler.java
/** * Create basic Message which contains all headers. No body is filled * /*from w w w . j a v a2 s . com*/ * @param session the Session * @param action the action * @return message * @throws AddressException * @throws MessagingException * @throws ActionException */ protected Message createMessage(Session session, A action) throws AddressException, MessagingException { MimeMessage message = new MimeMessage(session); SMTPMessage m = action.getMessage(); message.setFrom(new InternetAddress(m.getFrom())); userPreferences.addContact(m.getTo()); userPreferences.addContact(m.getCc()); userPreferences.addContact(m.getBcc()); message.setRecipients(RecipientType.TO, MessageUtils.getRecipients(m.getTo())); message.setRecipients(RecipientType.CC, MessageUtils.getRecipients(m.getCc())); message.setRecipients(RecipientType.BCC, MessageUtils.getRecipients(m.getBcc())); message.setSubject(MessageUtils.encodeTexts(m.getSubject())); message.saveChanges(); return message; }
From source file:net.sf.jclal.util.mail.SenderEmail.java
/** * Send the email with the indicated parameters * * @param subject The subject/*from w w w. ja va 2 s. c o m*/ * @param content The content * @param reportFile The reportFile to send */ public void sendEmail(String subject, String content, File reportFile) { // Get system properties Properties properties = new Properties(); // Setup mail server properties.setProperty("mail.smtp.host", host); properties.put("mail.smtp.port", port); if (!user.isEmpty() && !pass.isEmpty()) { properties.setProperty("mail.user", user); properties.setProperty("mail.password", pass); } // Get the default Session object. Session session = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipients(Message.RecipientType.TO, toRecipients.toString()); // Set Subject: header field message.setSubject(subject); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message messageBodyPart.setText(content); // Create a multipar message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); if (attachReporFile) { messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(reportFile))); messageBodyPart.setFileName(reportFile.getName()); multipart.addBodyPart(messageBodyPart); } // Send the complete message parts message.setContent(multipart); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException e) { Logger.getLogger(SenderEmail.class.getName()).log(Level.SEVERE, null, e); } }
From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java
protected void createInitialIMAPTestdata(final Properties props, final String user, final String password, final int count, final boolean deleteall) throws MessagingException { final Session session = Session.getInstance(props); final Store store = session.getStore(); store.connect(user, password);// ww w. ja v a 2 s .c o m checkStoreForTestConnection(store); final Folder root = store.getDefaultFolder(); final Folder testroot = root.getFolder("ES-IMAP-RIVER-TESTS"); final Folder testrootl2 = testroot.getFolder("Level(2!"); if (deleteall) { deleteMailsFromUserMailbox(props, "INBOX", 0, -1, user, password); if (testroot.exists()) { testroot.delete(true); } final Folder testrootenamed = root.getFolder("renamed_from_ES-IMAP-RIVER-TESTS"); if (testrootenamed.exists()) { testrootenamed.delete(true); } } if (!testroot.exists()) { testroot.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES); testroot.open(Folder.READ_WRITE); testrootl2.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES); testrootl2.open(Folder.READ_WRITE); } final Folder inbox = root.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); final Message[] msgs = new Message[count]; for (int i = 0; i < count; i++) { final MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(EMAIL_TO)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS)); message.setSubject(EMAIL_SUBJECT + "::" + i); message.setText(EMAIL_TEXT + "::" + SID++); message.setSentDate(new Date()); msgs[i] = message; } inbox.appendMessages(msgs); testroot.appendMessages(msgs); testrootl2.appendMessages(msgs); IMAPUtils.close(inbox); IMAPUtils.close(testrootl2); IMAPUtils.close(testroot); IMAPUtils.close(store); }