List of usage examples for javax.mail Session getInstance
public static Session getInstance(Properties props)
From source file:org.opens.emailsender.EmailSender.java
/** * * @param emailFrom/* w w w . j a v a 2s .c o m*/ * @param emailToSet * @param emailBccSet (can be null) * @param replyTo (can be null) * @param emailSubject * @param emailContent */ public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo, String emailSubject, String emailContent) { boolean debug = false; // Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); // create some properties and get the default Session Session session = Session.getInstance(props); session.setDebug(debug); try { Transport t = session.getTransport("smtp"); t.connect(smtpHost, userName, password); // create a message MimeMessage msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom; try { // Used default from address is passed one is null or empty or // blank addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom) : new InternetAddress(from); msg.setFrom(addressFrom); Address[] recipients = new InternetAddress[emailToSet.size()]; int i = 0; for (String emailTo : emailToSet) { recipients[i] = new InternetAddress(emailTo); i++; } msg.setRecipients(Message.RecipientType.TO, recipients); if (CollectionUtils.isNotEmpty(emailBccSet)) { Address[] bccRecipients = new InternetAddress[emailBccSet.size()]; i = 0; for (String emailBcc : emailBccSet) { bccRecipients[i] = new InternetAddress(emailBcc); i++; } msg.setRecipients(Message.RecipientType.BCC, bccRecipients); } if (StringUtils.isNotBlank(replyTo)) { Address[] replyToRecipients = { new InternetAddress(replyTo) }; msg.setReplyTo(replyToRecipients); } // Setting the Subject msg.setSubject(emailSubject, CHARSET_KEY); // Setting content and charset (warning: both declarations of // charset are needed) msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY); LOGGER.error("emailContent " + emailContent); msg.setContent(emailContent, FULL_CHARSET_KEY); try { LOGGER.debug("emailContent from message object " + msg.getContent().toString()); } catch (IOException ex) { LOGGER.error(ex.getMessage()); } catch (MessagingException ex) { LOGGER.error(ex.getMessage()); } for (Address addr : msg.getAllRecipients()) { LOGGER.error("addr " + addr); } t.sendMessage(msg, msg.getAllRecipients()); } catch (AddressException ex) { LOGGER.warn(ex.getMessage()); } } catch (NoSuchProviderException e) { LOGGER.warn(e.getMessage()); } catch (MessagingException e) { LOGGER.warn(e.getMessage()); } }
From source file:com.gitlab.anlar.lunatic.server.ServerTest.java
private void sendSinglePartEmail(String from, String to, String subject, String body) throws MessagingException { Properties props = createEmailProps(serverPort); Session session = Session.getInstance(props); Message msg = createBaseMessage(from, to, subject, session); msg.setText(body);//from w ww . j a v a 2s . c o m Transport.send(msg); }
From source file:org.asqatasun.emailsender.EmailSender.java
/** * * @param emailFrom/* w ww. j av a2s . c o m*/ * @param emailToSet * @param emailBccSet (can be null) * @param replyTo (can be null) * @param emailSubject * @param emailContent */ public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo, String emailSubject, String emailContent) { boolean debug = false; // Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); // create some properties and get the default Session Session session = Session.getInstance(props); session.setDebug(debug); try { Transport t = session.getTransport("smtp"); t.connect(smtpHost, userName, password); // create a message MimeMessage msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom; try { // Used default from address is passed one is null or empty or // blank addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom) : new InternetAddress(from); msg.setFrom(addressFrom); Address[] recipients = new InternetAddress[emailToSet.size()]; int i = 0; for (String emailTo : emailToSet) { recipients[i] = new InternetAddress(emailTo); i++; } msg.setRecipients(Message.RecipientType.TO, recipients); if (CollectionUtils.isNotEmpty(emailBccSet)) { Address[] bccRecipients = new InternetAddress[emailBccSet.size()]; i = 0; for (String emailBcc : emailBccSet) { bccRecipients[i] = new InternetAddress(emailBcc); i++; } msg.setRecipients(Message.RecipientType.BCC, bccRecipients); } if (StringUtils.isNotBlank(replyTo)) { Address[] replyToRecipients = { new InternetAddress(replyTo) }; msg.setReplyTo(replyToRecipients); } // Setting the Subject msg.setSubject(emailSubject, CHARSET_KEY); // Setting content and charset (warning: both declarations of // charset are needed) msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY); LOGGER.debug("emailContent " + emailContent); msg.setContent(emailContent, FULL_CHARSET_KEY); try { LOGGER.debug("emailContent from message object " + msg.getContent().toString()); } catch (IOException ex) { LOGGER.error(ex.getMessage()); } catch (MessagingException ex) { LOGGER.error(ex.getMessage()); } for (Address addr : msg.getAllRecipients()) { LOGGER.debug("addr " + addr); } t.sendMessage(msg, msg.getAllRecipients()); } catch (AddressException ex) { LOGGER.warn("AddressException " + ex.getMessage()); LOGGER.warn("AddressException " + ex.getStackTrace()); } } catch (NoSuchProviderException e) { LOGGER.warn("NoSuchProviderException " + e.getMessage()); LOGGER.warn("NoSuchProviderException " + e.getStackTrace()); } catch (MessagingException e) { LOGGER.warn("MessagingException " + e.getMessage()); LOGGER.warn("MessagingException " + e.getStackTrace()); } }
From source file:org.dspace.services.email.EmailServiceImpl.java
@Override public void init() { // See if there is already a Session in our environment String sessionName = cfg.getProperty("mail.session.name"); if (null == sessionName) { sessionName = "Session"; }/*from w w w . jav a 2 s . c o m*/ try { InitialContext ctx = new InitialContext(null); session = (Session) ctx.lookup("java:comp/env/mail/" + sessionName); } catch (NamingException ex) { logger.warn("Couldn't get an email session from environment: {}", ex.getMessage()); } if (null != session) { logger.info("Email session retrieved from environment."); } else { // No Session provided, so create one logger.info("Initializing an email session from configuration."); Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); String host = cfg.getProperty("mail.server"); if (null != host) { props.put("mail.host", cfg.getProperty("mail.server")); } String port = cfg.getProperty("mail.server.port"); if (null != port) { props.put("mail.smtp.port", port); } if (null == cfg.getProperty("mail.server.username")) { session = Session.getInstance(props); } else { props.put("mail.smtp.auth", "true"); session = Session.getInstance(props, this); } // Set extra configuration properties String extras = cfg.getProperty("mail.extraproperties"); if ((extras != null) && (!"".equals(extras.trim()))) { String arguments[] = extras.split(","); String key, value; for (String argument : arguments) { key = argument.substring(0, argument.indexOf('=')).trim(); value = argument.substring(argument.indexOf('=') + 1).trim(); props.put(key, value); } } } }
From source file:com.ieprofile.helper.gmail.OAuth2Authenticator.java
/** * Connects and authenticates to an IMAP server with OAuth2. You must have * called {@code initialize}.//from w w w. ja v a 2 s . c o m * * @param host Hostname of the imap server, for example {@code * imap.googlemail.com}. * @param port Port of the imap server, for example 993. * @param userEmail Email address of the user to authenticate, for example * {@code oauth@gmail.com}. * @param oauthToken The user's OAuth token. * @param debug Whether to enable debug logging on the IMAP connection. * * @return An authenticated IMAPStore that can be used for IMAP operations. */ public List<MessageBean> connectToImap(String host, int port, String userEmail, String oauthToken, boolean debug) throws Exception { Properties props = new Properties(); props.put("mail.imaps.sasl.enable", "true"); props.put("mail.imaps.sasl.mechanisms", "XOAUTH2"); props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken); Session session = Session.getInstance(props); session.setDebug(debug); final URLName unusedUrlName = null; IMAPSSLStore store = new IMAPSSLStore(session, unusedUrlName); final String emptyPassword = ""; store.connect(host, port, userEmail, emptyPassword); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_WRITE); Message messages[] = inbox.getMessages(); int messageCount = inbox.getMessageCount(); List<String> attachments = new ArrayList<String>(); LinkedList<MessageBean> listMessages = emailListener.sendMessage(messages, attachments); emailRepo.addAllMessages(listMessages); emailListener.folder = inbox; emailListener.started = false; emailListener.start(); //ArrayList<String> attachments = new ArrayList<String>(); //LinkedList<MessageBean> listMessages = getPart(messages, attachments); //store.close(); return emailRepo.getMessages(); }
From source file:com.gitlab.anlar.lunatic.server.ServerTest.java
private void sendMultiPartEmail(String from, String to, String subject, String body) throws MessagingException { Properties props = createEmailProps(serverPort); Session session = Session.getInstance(props); Message msg = createBaseMessage(from, to, subject, session); MimeBodyPart p1 = new MimeBodyPart(); p1.setText(body);/*from w ww.jav a 2 s. co m*/ MimeBodyPart p2 = new MimeBodyPart(); p2.setText("Second part"); Multipart mp = new MimeMultipart(); mp.addBodyPart(p1); mp.addBodyPart(p2); msg.setContent(mp); Transport.send(msg); }
From source file:be.fedict.eid.pkira.blm.model.mail.MailHandlerBean.java
@Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void onMessage(Message arg0) { ObjectMessage objectMessage = (ObjectMessage) arg0; try {/*from w w w . j a va 2 s . c o m*/ Mail mail = (Mail) objectMessage.getObject(); // Get properties String mailProtocol = getMailProtocol(); String mailServer = getSmtpServer(); String mailUser = getSmtpUser(); String mailPort = getSmtpPort(); String mailPassword = getSmtpPassword(); // Initialize a mail session Properties props = new Properties(); props.put("mail." + mailProtocol + ".host", mailServer); props.put("mail." + mailProtocol + ".port", mailPort); Session session = Session.getInstance(props); // Create the message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(mail.getSender())); for (String recipient : mail.getRecipients()) { msg.addRecipient(RecipientType.TO, new InternetAddress(recipient)); } msg.setSubject(mail.getSubject(), "UTF-8"); Multipart multipart = new MimeMultipart(); msg.setContent(multipart); // Set the email message text and attachment MimeBodyPart messagePart = new MimeBodyPart(); messagePart.setContent(mail.getBody(), mail.getContentType()); multipart.addBodyPart(messagePart); if (mail.getAttachmentData() != null) { ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(mail.getAttachmentData(), mail.getAttachmentContentType()); DataHandler dataHandler = new DataHandler(byteArrayDataSource); MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setDataHandler(dataHandler); attachmentPart.setFileName(mail.getAttachmentFileName()); multipart.addBodyPart(attachmentPart); } // Open transport and send message Transport transport = session.getTransport(mailProtocol); if (StringUtils.isNotBlank(mailUser)) { transport.connect(mailUser, mailPassword); } else { transport.connect(); } msg.saveChanges(); transport.sendMessage(msg, msg.getAllRecipients()); } catch (JMSException e) { errorLogger.logError(ApplicationComponent.MAIL, "Cannot handle the object message from the queue", e); throw new RuntimeException(e); } catch (MessagingException e) { errorLogger.logError(ApplicationComponent.MAIL, "Cannot send a mail message", e); throw new RuntimeException(e); } }
From source file:com.liferay.mail.imap.IMAPConnection.java
public Session getSession() { if (_session != null) { return _session; }// w w w. j a v a2 s . c o m Properties properties = new Properties(); properties.put("mail.debug", String.valueOf(PortletPropsValues.JAVAMAIL_DEBUG)); properties.put("mail.imap.host", _incomingHostName); properties.put("mail.imap.port", _incomingPort); properties.put("mail.imaps.auth", "true"); properties.put("mail.imaps.host", _incomingHostName); properties.put("mail.imaps.port", _incomingPort); properties.put("mail.imaps.socketFactory.class", SSLSocketFactory.class.getName()); properties.put("mail.imaps.socketFactory.fallback", "false"); properties.put("mail.imaps.socketFactory.port", _incomingPort); properties.put("mail.smtp.host", _outgoingHostName); properties.put("mail.smtp.port", _outgoingPort); properties.put("mail.smtps.auth", "true"); properties.put("mail.smtps.host", _outgoingHostName); properties.put("mail.smtps.port", _outgoingPort); properties.put("mail.smtps.socketFactory.class", SSLSocketFactory.class.getName()); properties.put("mail.smtps.socketFactory.fallback", "false"); properties.put("mail.smtps.socketFactory.port", _outgoingPort); _session = Session.getInstance(properties); _session.setDebug(PortletPropsValues.JAVAMAIL_DEBUG); return _session; }
From source file:gwtupload.sendmailsample.server.SendMailSampleServlet.java
@Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { try {//w w w .j a v a 2 s.co m String from = null, to = null, subject = "", body = ""; // create a new multipart content MimeMultipart multiPart = new MimeMultipart(); for (FileItem item : sessionFiles) { if (item.isFormField()) { if ("from".equals(item.getFieldName())) from = item.getString(); if ("to".equals(item.getFieldName())) to = item.getString(); if ("subject".equals(item.getFieldName())) subject = item.getString(); if ("body".equals(item.getFieldName())) body = item.getString(); } else { // add the file part to multipart content MimeBodyPart part = new MimeBodyPart(); part.setFileName(item.getName()); part.setDataHandler( new DataHandler(new ByteArrayDataSource(item.get(), item.getContentType()))); multiPart.addBodyPart(part); } } // add the text part to multipart content MimeBodyPart txtPart = new MimeBodyPart(); txtPart.setContent(body, "text/plain"); multiPart.addBodyPart(txtPart); // configure smtp server Properties props = System.getProperties(); props.put("mail.smtp.host", SMTP_SERVER); // create a new mail session and the mime message MimeMessage mime = new MimeMessage(Session.getInstance(props)); mime.setText(body); mime.setContent(multiPart); mime.setSubject(subject); mime.setFrom(new InternetAddress(from)); for (String rcpt : to.split("[\\s;,]+")) mime.addRecipient(Message.RecipientType.TO, new InternetAddress(rcpt)); // send the message Transport.send(mime); } catch (MessagingException e) { throw new UploadActionException(e.getMessage()); } return "Your mail has been sent successfuly."; }
From source file:org.apache.falcon.plugin.EmailNotification.java
private void initialize() throws FalconException { Properties emailProperties = new Properties(); if (StringUtils.isEmpty(SMTP_HOST) && StringUtils.isEmpty(SMTP_PORT) && StringUtils.isEmpty(SMTP_FROM)) { LOG.error("SMTP properties is not defined in startup.properties"); return;/*from ww w .j av a 2 s .c om*/ } emailProperties.setProperty("mail.smtp.host", SMTP_HOST); emailProperties.setProperty("mail.smtp.port", SMTP_PORT); emailProperties.setProperty("mail.smtp.auth", SMTP_AUTH.toString()); try { Session session; if (!SMTP_AUTH) { session = Session.getInstance(emailProperties); } else { session = Session.getInstance(emailProperties, new FalconMailAuthenticator(SMTP_USER, SMTP_PASSWORD)); } message = new MimeMessage(session); message.setFrom(new InternetAddress(SMTP_FROM)); } catch (MessagingException e) { throw new FalconException("Exception occurred in SMTP initialization:" + e); } }