List of usage examples for javax.mail Session getInstance
public static Session getInstance(Properties props)
From source file:com.github.thorqin.webapi.mail.MailService.java
private void doSendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); Session session;/*from ww w.j av a 2 s. c om*/ props.put("mail.smtp.auth", String.valueOf(serverConfig.useAuthentication())); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", serverConfig.getHost()); if (serverConfig.getPort() != null) { props.put("mail.smtp.port", serverConfig.getPort()); } if (serverConfig.getSecure().equals(MailConfig.SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else if (serverConfig.getSecure().equals(MailConfig.SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", serverConfig.getPort()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else { if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } // Uncomment to show SMTP protocal // session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (serverConfig.getFrom() != null) message.setFrom(new InternetAddress(serverConfig.getFrom())); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (serverConfig.enableTrace()) { MailInfo info = new MailInfo(); info.recipients = mail.to; info.sender = StringUtil.join(message.getFrom()); info.smtpServer = serverConfig.getHost(); info.smtpUser = serverConfig.getUsername(); info.subject = mail.subject; info.startTime = beginTime; info.runningTime = System.currentTimeMillis() - beginTime; MonitorService.record(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:com.glaf.mail.MxMailHelper.java
public Mail getMail(InputStream inputStream) { try {//from ww w .j a v a 2 s.co m Properties props = new Properties(); props.put("mail.pop3.host", "abcd.com"); Session session = Session.getInstance(props); MimeMessage mimeMessage = new MimeMessage(session, inputStream); Object body = mimeMessage.getContent(); Mail mail = new Mail(); if (body instanceof Multipart) { processMultipart((Multipart) body, mail); } else { processPart(mimeMessage, mail); } return mail; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:com.spartasystems.holdmail.smtp.OutgoingMailSender.java
protected Session getMailSession() { Properties props = new Properties(); props.put("mail.smtp.auth", "false"); props.put("mail.smtp.starttls.enable", "false"); props.put("mail.smtp.host", getOutgoingServer()); props.put("mail.smtp.port", getOutgoingPort()); return Session.getInstance(props); }
From source file:com.yfiton.notifiers.email.EmailNotifierTest.java
private boolean checkEmailReception(String subject, String host, String username, String password) throws MessagingException { Properties properties = new Properties(); properties.put("mail.store.protocol", "imaps"); Session session = Session.getInstance(properties); Store store = null;//from ww w. j av a 2 s . com try { store = session.getStore("imaps"); store.connect(host, username, password); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); Message[] messages = inbox.getMessages(); for (Message message : messages) { if (message.getSubject().equals(subject)) { message.setFlag(Flags.Flag.DELETED, true); return true; } } inbox.close(true); } finally { try { if (store != null) { store.close(); } } catch (MessagingException e) { e.printStackTrace(); } } return false; }
From source file:org.jevis.emaildatasource.EMailManager.java
/** * Create special EMail Connection/*from w ww . j a v a2s. c om*/ * * @param parameters * * @return EMailConnection */ public static EMailConnection createConnection(EMailServerParameters parameters) { EMailConnection conn = null; Properties props = createProperties(parameters); Session session = Session.getInstance(props); if (parameters.getProtocol().equalsIgnoreCase(EMailConstants.Protocol.IMAP)) { conn = new IMAPConnection(); conn.setConnection(session, parameters); } else if (parameters.getProtocol().equalsIgnoreCase(EMailConstants.Protocol.POP3)) { conn = new POP3Connection(); conn.setConnection(session, parameters); } else { Logger.getLogger(EMailManager.class.getName()).log(Level.SEVERE, "EMail Connection failed"); } return conn; }
From source file:org.projectforge.mail.SendMail.java
private void sendIt(final Mail composedMessage) { final Session session = Session.getInstance(properties); Transport transport = null;/*ww w . j ava 2 s .co m*/ try { MimeMessage message = new MimeMessage(session); if (composedMessage.getFrom() != null) { message.setFrom(new InternetAddress(composedMessage.getFrom())); } else { message.setFrom(); } message.setRecipients(Message.RecipientType.TO, composedMessage.getTo()); String subject; subject = composedMessage.getSubject(); /* * try { subject = MimeUtility.encodeText(composedMessage.getSubject()); } catch (UnsupportedEncodingException ex) { * log.error("Exception encountered while encoding subject." + ex, ex); subject = composedMessage.getSubject(); } */ message.setSubject(subject, sendMailConfig.getCharset()); message.setSentDate(new Date()); if (composedMessage.getContentType() != null) { message.setText(composedMessage.getContent(), composedMessage.getCharset(), composedMessage.getContentType()); } else { message.setText(composedMessage.getContent(), sendMailConfig.getCharset()); } message.saveChanges(); // don't forget this transport = session.getTransport(); if (StringUtils.isNotEmpty(sendMailConfig.getUser()) == true) { transport.connect(sendMailConfig.getUser(), sendMailConfig.getPassword()); } else { transport.connect(); } transport.sendMessage(message, message.getAllRecipients()); } catch (MessagingException ex) { log.error("While creating and sending message: " + composedMessage.toString(), ex); throw new InternalErrorException("mail.error.exception"); } finally { if (transport != null) { try { transport.close(); } catch (MessagingException ex) { log.error("While creating and sending message: " + composedMessage.toString(), ex); throw new InternalErrorException("mail.error.exception"); } } } log.info("E-Mail successfully sent: " + composedMessage.toString()); }
From source file:com.ieprofile.helper.gmail.OAuth2Authenticator.java
/** * Connects and authenticates to an SMTP server with OAuth2. You must have * called {@code initialize}.//from www . java 2 s. c o m * * @param host Hostname of the smtp server, for example {@code * smtp.googlemail.com}. * @param port Port of the smtp server, for example 587. * @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 connection. * * @return An authenticated SMTPTransport that can be used for SMTP * operations. */ public static SMTPTransport connectToSmtp(String host, int port, String userEmail, String oauthToken, boolean debug) throws Exception { Properties props = new Properties(); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.starttls.required", "true"); props.put("mail.smtp.sasl.enable", "true"); props.put("mail.smtp.sasl.mechanisms", "XOAUTH2"); props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken); Session session = Session.getInstance(props); session.setDebug(debug); final URLName unusedUrlName = null; SMTPTransport transport = new SMTPTransport(session, unusedUrlName); // If the password is non-null, SMTP tries to do AUTH LOGIN. final String emptyPassword = ""; transport.connect(host, port, userEmail, emptyPassword); return transport; }
From source file:com.googlecode.gmail4j.javamail.ImapGmailConnection.java
public static IMAPStore 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);/*from w ww . j av a 2 s .co m*/ final URLName unusedUrlName = null; IMAPSSLStore store = new IMAPSSLStore(session, unusedUrlName); final String emptyPassword = ""; store.connect(host, port, userEmail, emptyPassword); return store; }
From source file:org.fireflow.service.email.send.MailSenderImpl.java
public void sendEMail(MailMessage mailMessage) throws ServiceInvocationException { //1?Session/*from w w w . j av a2 s . co m*/ Properties javaMailProperties = new Properties(); javaMailProperties.put("mail.transport.protocol", mailServiceDef.getProtocol()); javaMailProperties.put("mail.smtp.host", mailServiceDef.getSmtpServer()); javaMailProperties.put("mail.smtp.auth", mailServiceDef.isNeedAuth() ? "true" : "false"); if (mailServiceDef.isUseSSL()) { javaMailProperties.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); javaMailProperties.setProperty("mail.smtp.socketFactory.fallback", "false"); javaMailProperties.setProperty("mail.smtp.socketFactory.port", Integer.toString(mailServiceDef.getSmtpPort())); } Session mailSession = Session.getInstance(javaMailProperties); //2?MimeMessage MimeMessage mimeMsg = null; try { mimeMsg = createMimeMessage(mailSession, mailMessage); //3??? Transport transport = mailSession.getTransport(); transport.connect(mailServiceDef.getUserName(), mailServiceDef.getPassword()); transport.sendMessage(mimeMsg, mimeMsg.getAllRecipients()); } catch (AddressException e) { throw new ServiceInvocationException(e); } catch (MessagingException e) { throw new ServiceInvocationException(e); } }
From source file:com.github.thorqin.toolkit.mail.MailService.java
private void sendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); final Session session; props.put("mail.smtp.auth", String.valueOf(setting.auth)); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", setting.host); props.put("mail.smtp.port", setting.port); if (setting.secure.equals(SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); } else if (setting.secure.equals(SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", setting.port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); }// w w w . j a va2 s .c om if (!setting.auth) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(setting.user, setting.password); } }); if (setting.debug) session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (setting.from != null) message.setFrom(new InternetAddress(setting.from)); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (setting.trace && tracer != null) { Tracer.Info info = new Tracer.Info(); info.catalog = "mail"; info.name = "send"; info.put("sender", StringUtils.join(message.getFrom())); info.put("recipients", mail.to); info.put("SMTPServer", setting.host); info.put("SMTPAccount", setting.user); info.put("subject", mail.subject); info.put("startTime", beginTime); info.put("runningTime", System.currentTimeMillis() - beginTime); tracer.trace(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }