List of usage examples for javax.mail.internet MimeMessage setFrom
public void setFrom(String address) throws MessagingException
From source file:org.squale.squalecommon.util.mail.javamail.JavaMailProviderImpl.java
/** * This method send mail/*from w ww .j a v a 2 s . 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:edu.harvard.med.screensaver.service.SmtpEmailService.java
private void sendMessage(String subject, String message, InternetAddress from, InternetAddress[] recipients, InternetAddress[] cclist, File attachedFile) throws MessagingException, IOException { log.info("try to send: " + printEmail(subject, message, from, this.replyTos, recipients, cclist, (attachedFile == null ? "" : "" + attachedFile.getCanonicalFile()))); log.info("host: " + host + ", useSMTPS: " + useSmtps); Properties props = new Properties(); String protocol = "smtp"; if (useSmtps) // need smtps to test with gmail {/*from w ww. jav a 2 s.c om*/ props.put("mail.smtps.auth", "true"); protocol = "smtps"; } Session session = Session.getDefaultInstance(props, null); Transport t = session.getTransport(protocol); try { MimeMessage msg = new MimeMessage(session); if (this.replyTos != null) msg.setReplyTo(replyTos); msg.setFrom(from); msg.setSubject(subject); if (attachedFile != null) { setFileAsAttachment(msg, message, attachedFile); } else { msg.setContent(message, "text/plain"); } msg.addRecipients(Message.RecipientType.TO, recipients); if (cclist != null) msg.addRecipients(Message.RecipientType.CC, cclist); t.connect(host, username, password); t.sendMessage(msg, msg.getAllRecipients()); } finally { t.close(); } log.info("sent: " + printEmailHeader(subject, from, this.replyTos, recipients, cclist, (attachedFile == null ? "" : "" + attachedFile.getCanonicalFile()))); }
From source file:org.pentaho.platform.repository.subscription.SubscriptionEmailContent.java
public boolean send() { String cc = null;/* w w w. ja v a 2s. c o m*/ String bcc = null; String from = props.getProperty("mail.from.default"); String to = props.getProperty("to"); 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 { // Get a Session object Session session; if (authenticate) { Authenticator authenticator = new EmailAuthenticator(); 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)); } 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 (body != null) { MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(body, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ multipart.addBodyPart(textBodyPart); } // need to create a multi-part message... // create the Multipart and add its parts to it // create and fill the first message part IPentahoStreamSource source = attachment; if (source == null) { logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$ return false; } DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source); // create the second message part MimeBodyPart attachmentBodyPart = new MimeBodyPart(); // attach the file to the message attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(attachmentName); multipart.addBodyPart(attachmentBodyPart); // add the Multipart to the message msg.setContent(multipart); msg.setHeader("X-Mailer", SubscriptionEmailContent.MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); return true; // TODO: persist the content set for a while... } 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:com.fsrin.menumine.common.message.MailSenderImpl.java
/** * @see com.ess.messages.MailSender#send() *//* w w w.ja v a 2s . c o m*/ public boolean send() { try { Properties props = new Properties(); props.put("mail.smtp.host", host.getAddress()); if (host.useAuthentication()) { props.put("mail.smtp.auth", "true"); } Session s = Session.getInstance(props, null); s.setDebug(true); // PasswordAuthentication pa = new PasswordAuthentication(host // .getUsername(), host.getPassword()); // // URLName url = new URLName(host.getAddress()); // // s.setPasswordAuthentication(url, pa); MimeMessage messageOut = new MimeMessage(s); InternetAddress fromOut = new InternetAddress(from.getAddress()); //reid 2004-12-20 fromOut.setPersonal(from.getName()); messageOut.setFrom(fromOut); InternetAddress toOut = new InternetAddress(this.to.getAddress()); //reid 2004-12-20 toOut.setPersonal(to.getName()); messageOut.addRecipient(javax.mail.Message.RecipientType.TO, toOut); messageOut.setSubject(message.getSubject()); messageOut.setText(message.getMessage()); if (host.useAuthentication()) { Transport transport = s.getTransport("smtp"); transport.connect(host.getAddress(), host.getUsername(), host.getPassword()); transport.sendMessage(messageOut, messageOut.getAllRecipients()); transport.close(); } else { Transport.send(messageOut); } } catch (Exception e) { log.info("\n\nMailSenderIMPL3: " + host.getAddress()); e.printStackTrace(); throw new RuntimeException(e); } return true; }
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 . j ava2 s . c o 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:org.wandora.piccolo.actions.SendEmail.java
public void doAction(User user, javax.servlet.ServletRequest request, javax.servlet.ServletResponse response, Application application) {//from www. ja v a 2 s .c o m try { Properties props = new Properties(); props.put("mail.smtp.host", smtpServer); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); if (subject != null) message.setSubject(subject); if (from != null) message.setFrom(new InternetAddress(from)); Vector<String> recipients = new Vector<String>(); if (recipient != null) { String[] rs = recipient.split(","); String r = null; for (int i = 0; i < rs.length; i++) { r = rs[i]; if (r != null) recipients.add(r); } } MimeMultipart multipart = new MimeMultipart(); Template template = application.getTemplate(emailTemplate, user); HashMap context = new HashMap(); context.put("request", request); context.put("message", message); context.put("recipients", recipients); context.put("emailhelper", new MailHelper()); context.put("multipart", multipart); context.putAll(application.getDefaultContext(user)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); template.process(context, baos); MimeBodyPart mimeBody = new MimeBodyPart(); mimeBody.setContent(new String(baos.toByteArray(), template.getEncoding()), template.getMimeType()); // mimeBody.setContent(baos.toByteArray(),template.getMimeType()); multipart.addBodyPart(mimeBody); message.setContent(multipart); Transport transport = session.getTransport("smtp"); transport.connect(smtpServer, smtpUser, smtpPass); Address[] recipientAddresses = new Address[recipients.size()]; for (int i = 0; i < recipientAddresses.length; i++) { recipientAddresses[i] = new InternetAddress(recipients.elementAt(i)); } transport.sendMessage(message, recipientAddresses); } catch (Exception e) { logger.writelog("WRN", e); } }
From source file:tsuboneSystem.original.manager.MailManager.java
/** * ?//from w ww .j a va2s . com * @return */ public boolean sendMail() { //???TRUE if (!check()) { return false; } Properties objPrp = new Properties(); objPrp.setProperty("mail.smtp.host", "smtp.gmail.com"); objPrp.setProperty("mail.smtp.port", "465"); objPrp.setProperty("mail.smtp.auth", "true"); // objPrp.setProperty("mail.smtp.connectiontimeout", "5000"); objPrp.setProperty("mail.smtp.timeout", "5000"); //???????????JavaMail?Message-ID????? objPrp.setProperty("mail.user", "kagucho.net@gmail.com"); objPrp.setProperty("mail.host", "smtp.gmail.com"); //???????? objPrp.setProperty("mail.debug", "true"); // SSL objPrp.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); objPrp.setProperty("mail.smtp.socketFactory.fallback", "false"); objPrp.setProperty("mail.smtp.socketFactory.port", "465"); String address = ConfigUtil.getConfig("mail.address"); String pw = ConfigUtil.getConfig("mail.pw"); // Session session = Session.getInstance(objPrp, new PlainAuthenticator(address, pw)); // ?? MimeMessage objMsg = new MimeMessage(session); try { // ? objMsg.setFrom(new InternetAddress(address, displayName)); // ?? objMsg.setSubject(title, encoding); // ?TO????CCBCC? objMsg.setRecipients(Message.RecipientType.BCC, getToAddress()); // objMsg.setText(getContent(), encoding); // ? SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); try { t.connect("smtp.gmail.com", address, pw); t.sendMessage(objMsg, objMsg.getAllRecipients()); } finally { t.close(); } return false; } catch (UnsupportedEncodingException e) { e.printStackTrace(); return true; } catch (MessagingException e) { e.printStackTrace(); return true; } }
From source file:org.openmeetings.test.calendar.TestSendIcalMessage.java
private void sendIcalMessage() throws Exception { log.debug("sendIcalMessage"); // Evaluating Configuration Data String smtpServer = cfgManagement.getConfKey(3, "smtp_server").getConf_value(); String smtpPort = cfgManagement.getConfKey(3, "smtp_port").getConf_value(); // String from = "openmeetings@xmlcrm.org"; String from = cfgManagement.getConfKey(3, "system_email_addr").getConf_value(); String emailUsername = cfgManagement.getConfKey(3, "email_username").getConf_value(); String emailUserpass = cfgManagement.getConfKey(3, "email_userpass").getConf_value(); Properties props = System.getProperties(); props.put("mail.smtp.host", smtpServer); props.put("mail.smtp.port", smtpPort); Configuration conf = cfgManagement.getConfKey(3, "mail.smtp.starttls.enable"); if (conf != null) { if (conf.getConf_value().equals("1")) { props.put("mail.smtp.starttls.enable", "true"); }/* w w w .java 2 s .c o m*/ } // Check for Authentification Session session = null; if (emailUsername != null && emailUsername.length() > 0 && emailUserpass != null && emailUserpass.length() > 0) { // use SMTP Authentication props.put("mail.smtp.auth", "true"); session = Session.getDefaultInstance(props, new SmtpAuthenticator(emailUsername, emailUserpass)); } else { // not use SMTP Authentication session = Session.getDefaultInstance(props, null); } // Building MimeMessage MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setSubject(subject); mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients, false)); // -- Create a new message -- BodyPart msg = new MimeBodyPart(); msg.setDataHandler(new DataHandler(new ByteArrayDataSource(htmlBody, "text/html; charset=\"utf-8\""))); Multipart multipart = new MimeMultipart(); BodyPart iCalAttachment = new MimeBodyPart(); iCalAttachment.setDataHandler(new DataHandler(new javax.mail.util.ByteArrayDataSource( new ByteArrayInputStream(iCalMimeBody), "text/calendar;method=REQUEST;charset=\"UTF-8\""))); iCalAttachment.setFileName("invite.ics"); multipart.addBodyPart(iCalAttachment); multipart.addBodyPart(msg); mimeMessage.setSentDate(new Date()); mimeMessage.setContent(multipart); // -- Set some other header information -- // mimeMessage.setHeader("X-Mailer", "XML-Mail"); // mimeMessage.setSentDate(new Date()); // Transport trans = session.getTransport("smtp"); Transport.send(mimeMessage); }
From source file:gov.nih.nci.cabig.caaers.esb.client.MessageNotificationService.java
public void sendMail(String[] to, String subject, String content, String attachment) throws Exception { MimeMessage message = caaersJavaMailSender.createMimeMessage(); message.setSubject(subject);//from w w w .j ava2s . com message.setFrom(new InternetAddress(configuration.get(Configuration.SYSTEM_FROM_EMAIL))); // use the true flag to indicate you need a multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setText(content); if (attachment != null) { File f = new File(attachment); FileSystemResource file = new FileSystemResource(f); helper.addAttachment(file.getFilename(), file); } caaersJavaMailSender.send(message); }
From source file:com.reizes.shiva.net.mail.Mail.java
public void sendHtmlMail(String fromName, String from, String to, String cc, String bcc, String subject, String content) throws UnsupportedEncodingException, MessagingException { boolean parseStrict = false; MimeMessage message = new MimeMessage(getSessoin()); InternetAddress address = InternetAddress.parse(from, parseStrict)[0]; if (fromName != null) { address.setPersonal(fromName, charset); }//from ww w. j a va2 s. co m message.setFrom(address); message.setRecipients(Message.RecipientType.TO, parseAddresses(to)); if (cc != null) { message.setRecipients(Message.RecipientType.CC, parseAddresses(cc)); } if (bcc != null) { message.setRecipients(Message.RecipientType.BCC, parseAddresses(bcc)); } message.setSubject(subject, charset); message.setHeader("X-Mailer", "sendMessage"); message.setSentDate(new java.util.Date()); // Multipart multipart = new MimeMultipart(); MimeBodyPart bodypart = new MimeBodyPart(); bodypart.setContent(content, "text/html; charset=" + charset); multipart.addBodyPart(bodypart); message.setContent(multipart); Transport.send(message); }