javax.mail.Authenticator Java Examples

The following examples show how to use javax.mail.Authenticator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: journaldev   Author: journaldev   File: TLSEmail.java    License: MIT License 8 votes vote down vote up
/**
   Outgoing Mail (SMTP) Server
   requires TLS or SSL: smtp.gmail.com (use authentication)
   Use Authentication: Yes
   Port for TLS/STARTTLS: 587
 */
public static void main(String[] args) {
	final String fromEmail = "[email protected]";
	final String password = "Tata!!11";
	final String toEmail = "[email protected]";
	
	System.out.println("TLSEmail Start");
	Properties props = new Properties();
	props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
	props.put("mail.smtp.port", "587"); //TLS Port
	props.put("mail.smtp.auth", "true"); //enable authentication
	props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
	
	Authenticator auth = new Authenticator() {
		//override the getPasswordAuthentication method
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(fromEmail, password);
		}
	};
	Session session = Session.getInstance(props, auth);
	
	EmailUtil.sendEmail(session, toEmail,"TLSEmail Testing Subject", "TLSEmail Testing Body");
	
}
 
Example #2
Source Project: Open-Lowcode   Author: openlowcode   File: MailDaemon.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * connects securely to the SMTP server (with authentication)
 * 
 * @return the SMTP session
 */
private Session connectAuthenticatedToServer() {
	Properties props = new Properties();
	props.put("mail.smtp.host", smtpserver); // SMTP Host
	props.put("mail.smtp.socketFactory.port", port); // SSL Port
	props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // SSL Factory Class
	props.put("mail.smtp.auth", "true"); // Enabling SMTP Authentication
	props.put("mail.smtp.port", port); // SMTP Port

	Authenticator auth = new Authenticator() {
		// override the getPasswordAuthentication method
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(user, password);
		}
	};

	Session session = Session.getDefaultInstance(props, auth);
	return session;
}
 
Example #3
Source Project: smart-admin   Author: 1024-lab   File: SmartSendMailUtil.java    License: MIT License 6 votes vote down vote up
/**
 * 创建session
 *
 * @author lidoudou
 * @date 2019/2/16 14:59
 */
private static Session createSSLSession(String sendSMTPHost, String port, String userName, String pwd) {
    // 1. 创建参数配置, 用于连接邮件服务器的参数配置
    Properties props = new Properties(); // 参数配置

    props.setProperty("mail.smtp.user", userName);
    props.setProperty("mail.smtp.password", pwd);
    props.setProperty("mail.smtp.host", sendSMTPHost);
    props.setProperty("mail.smtp.port", port);
    props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.socketFactory.port", port);
    props.put("mail.smtp.auth", "true");

    // 2. 根据配置创建会话对象, 用于和邮件服务器交互
    Session session = Session.getDefaultInstance(props, new Authenticator() {
        //身份认证
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, pwd);
        }
    });
    session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log
    return session;
}
 
Example #4
Source Project: mzmine3   Author: mzmine   File: ErrorMail.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void sendErrorEmail(String emailTo, String emailFrom, String smtpServer, String subject,
    String msg, String password, Integer port) throws IOException {

  Properties props = new Properties();
  props.put("mail.smtp.host", smtpServer); // SMTP Host
  props.put("mail.smtp.socketFactory.port", port); // SSL Port
  props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // SSL Factory
                                                                                // Class
  props.put("mail.smtp.auth", "true"); // Enabling SMTP Authentication
  props.put("mail.smtp.port", port); // SMTP Port, gmail 465

  Authenticator auth = new Authenticator() {

    // override the getPasswordAuthentication method
    protected PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(emailFrom, password);
    }
  };
  Session session = Session.getDefaultInstance(props, auth);
  Thread eMailThread = new Thread(new EMailUtil(session, emailTo, subject, msg));
  eMailThread.start();
}
 
Example #5
Source Project: personal_book_library_web_project   Author: batux   File: EmailSender.java    License: MIT License 6 votes vote down vote up
private Session getSession() {
	
	if(session == null) {
		
		final String fromEmail = environment.getProperty("from.email");
		final String password = environment.getProperty("email.password");
		
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.port", "587");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		
		Authenticator auth = new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(fromEmail, password);
			}
		};
		
		this.session = Session.getInstance(props, auth);
	}
	
	return session;
}
 
Example #6
Source Project: localization_nifi   Author: wangrenlei   File: EmailNotificationService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Based on the input properties, determine whether an authenticate or unauthenticated session should be used. If authenticated, creates a Password Authenticator for use in sending the email.
 *
 * @param properties mail properties
 * @return session
 */
private Session createMailSession(final Properties properties) {
    String authValue = properties.getProperty("mail.smtp.auth");
    Boolean auth = Boolean.valueOf(authValue);

    /*
     * Conditionally create a password authenticator if the 'auth' parameter is set.
     */
    final Session mailSession = auth ? Session.getInstance(properties, new Authenticator() {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            String username = properties.getProperty("mail.smtp.user"), password = properties.getProperty("mail.smtp.password");
            return new PasswordAuthentication(username, password);
        }
    }) : Session.getInstance(properties); // without auth

    return mailSession;
}
 
Example #7
Source Project: localization_nifi   Author: wangrenlei   File: PutEmail.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Based on the input properties, determine whether an authenticate or unauthenticated session should be used. If authenticated, creates a Password Authenticator for use in sending the email.
 *
 * @param properties mail properties
 * @return session
 */
private Session createMailSession(final Properties properties) {
    String authValue = properties.getProperty("mail.smtp.auth");
    Boolean auth = Boolean.valueOf(authValue);

    /*
     * Conditionally create a password authenticator if the 'auth' parameter is set.
     */
    final Session mailSession = auth ? Session.getInstance(properties, new Authenticator() {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            String username = properties.getProperty("mail.smtp.user"), password = properties.getProperty("mail.smtp.password");
            return new PasswordAuthentication(username, password);
        }
    }) : Session.getInstance(properties); // without auth
    return mailSession;
}
 
Example #8
Source Project: jivejdon   Author: banq   File: EmailTask.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Reads mail properties creates a JavaMail session that will be used to
 * send all mail.
 */
public EmailTask(String host, String port, String debug, String user, String password, String from) {
	this();
	Properties mailProps = new Properties();
	if (host != null) {
		mailProps.setProperty("mail.smtp.host", host);
	}
	// check the port for errors (if specified)
	if (port != null && !port.equals("")) {
		try {
			// no errors at this point, so add the port as a property
			mailProps.setProperty("mail.smtp.port", port);
		} catch (Exception e) {
		}
	}
	// optional mail debug (output is written to standard out)
	if ("true".equals(debug)) {
		mailProps.setProperty("mail.debug", "true");
	}
	mailProps.put("mail.smtp.auth", "true");
	mailProps.put("mail.smtp.from", from);

	// Create the mail session
	Authenticator auth = new SMTPAuthenticator(user, password);
	session = Session.getDefaultInstance(mailProps, auth);
}
 
Example #9
Source Project: phoebus   Author: ControlSystemStudio   File: EmailApp.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Create the {@link Session} at startup
 */
@Override
public void start()
{
    final Properties props = new Properties();
    props.put("mail.smtp.host", EmailPreferences.mailhost);
    props.put("mail.smtp.port", EmailPreferences.mailport);

    final String username = EmailPreferences.username;
    final String password = EmailPreferences.password;

    if (!username.isEmpty() && !password.isEmpty()) {
        PasswordAuthentication auth = new PasswordAuthentication(username, password);
        session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return auth;
            }
        });
    } else {
        session = Session.getDefaultInstance(props);
    }
}
 
Example #10
Source Project: EasyML   Author: ICT-BDA   File: JavaMail.java    License: Apache License 2.0 6 votes vote down vote up
public boolean sendMsg(String recipient, String subject, String content)
		throws MessagingException {
	// Create a mail object
	Session session = Session.getInstance(props, new Authenticator() {
		// Set the account information session,transport will send mail
		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(Constants.MAIL_USERNAME, Constants.MAIL_PASSWORD);
		}
	});
	session.setDebug(true);
	Message msg = new MimeMessage(session);
	try {
		msg.setSubject(subject);			//Set the mail subject
		msg.setContent(content,"text/html;charset=utf-8");
		msg.setFrom(new InternetAddress(Constants.MAIL_USERNAME));			//Set the sender
		msg.setRecipient(RecipientType.TO, new InternetAddress(recipient));	//Set the recipient
		Transport.send(msg);
		return true;
	} catch (Exception ex) {
		ex.printStackTrace();
		System.out.println(ex.getMessage());
		return false;
	}

}
 
Example #11
Source Project: development   Author: servicecatalog   File: PortalTester.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * initialize java mail session
 */
private void initMailSession() {

    address = prop.getProperty(EMAIL_ADDRESS);
    String host = prop.getProperty(EMAIL_HOST);
    final String user = prop.getProperty(EMAIL_USER);
    final String password = prop.getProperty(EMAIL_PASSWORD);
    String protocol = prop.getProperty(EMAIL_PROTOCOL);

    emailProp = new Properties();
    emailProp.setProperty("mail.store.protocol", protocol);
    emailProp.setProperty("mail.host", host);
    emailProp.setProperty("mail.user", user);
    emailProp.setProperty("mail.from", address);
    emailProp.setProperty("mail.debug", "true");

    mailSession = Session.getInstance(emailProp, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, password);
        }
    });
}
 
Example #12
Source Project: mzmine2   Author: mzmine   File: ErrorMail.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void sendErrorEmail(String emailTo, String emailFrom, String smtpServer, String subject,
     String msg, String password, Integer port) throws IOException {

   Properties props = new Properties();
   props.put("mail.smtp.host", smtpServer); // SMTP Host
   props.put("mail.smtp.socketFactory.port", port); // SSL Port
   props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // SSL Factory
                                                                                 // Class
   props.put("mail.smtp.auth", "true"); // Enabling SMTP Authentication
   props.put("mail.smtp.port", port); // SMTP Port, gmail 465

   Authenticator auth = new Authenticator() {

     // override the getPasswordAuthentication method
     protected PasswordAuthentication getPasswordAuthentication() {
       return new PasswordAuthentication(emailFrom, password);
     }
   };
   Session session = Session.getDefaultInstance(props, auth);
   Thread eMailThread = new Thread(new EMailUtil(session, emailTo, subject, msg));
eMailThread.start();
 }
 
Example #13
Source Project: Eagle   Author: eBay   File: EagleMailClient.java    License: Apache License 2.0 6 votes vote down vote up
public EagleMailClient(AbstractConfiguration configuration) {
	try {
		ConcurrentMapConfiguration con = (ConcurrentMapConfiguration)configuration;
		velocityEngine = new VelocityEngine();
		velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
		velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
		velocityEngine.init();

		con.setProperty("mail.transport.protocol", "smtp");
		final Properties config = con.getProperties();
		if(Boolean.parseBoolean(config.getProperty(AUTH_CONFIG))){
			session = Session.getDefaultInstance(config, new Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(config.getProperty(USER_CONFIG), config.getProperty(PWD_CONFIG));
				}
			});
		}
		else session = Session.getDefaultInstance(config, new Authenticator() {});
		final String debugMode =  config.getProperty(DEBUG_CONFIG, "false");
		final boolean debug =  Boolean.parseBoolean(debugMode);
		session.setDebug(debug);
	} catch (Exception e) {
           LOG.error("Failed connect to smtp server",e);
	}
}
 
Example #14
Source Project: ogham   Author: groupe-sii   File: UsernamePasswordAuthenticatorBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Authenticator build() {
	boolean isUpdatable = updatableValueBuilder.getValue(false);
	if (isUpdatable) {
		if (usernameValueBuilder.hasValueOrProperties() && passwordValueBuilder.hasValueOrProperties()) {
			return buildContext.register(new UpdatableUsernamePasswordAuthenticator(usernameValueBuilder, passwordValueBuilder));
		}
		return null;
	}
	String u = usernameValueBuilder.getValue();
	String p = passwordValueBuilder.getValue();
	if (u != null && p != null) {
		return buildContext.register(new UsernamePasswordAuthenticator(u, p));
	}
	return null;
}
 
Example #15
Source Project: nifi   Author: apache   File: EmailNotificationService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Based on the input properties, determine whether an authenticate or unauthenticated session should be used. If authenticated, creates a Password Authenticator for use in sending the email.
 *
 * @param properties mail properties
 * @return session
 */
private Session createMailSession(final Properties properties) {
    String authValue = properties.getProperty("mail.smtp.auth");
    Boolean auth = Boolean.valueOf(authValue);

    /*
     * Conditionally create a password authenticator if the 'auth' parameter is set.
     */
    final Session mailSession = auth ? Session.getInstance(properties, new Authenticator() {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            String username = properties.getProperty("mail.smtp.user"), password = properties.getProperty("mail.smtp.password");
            return new PasswordAuthentication(username, password);
        }
    }) : Session.getInstance(properties); // without auth

    return mailSession;
}
 
Example #16
Source Project: nifi   Author: apache   File: PutEmail.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Based on the input properties, determine whether an authenticate or unauthenticated session should be used. If authenticated, creates a Password Authenticator for use in sending the email.
 *
 * @param properties mail properties
 * @return session
 */
private Session createMailSession(final Properties properties) {
    String authValue = properties.getProperty("mail.smtp.auth");
    Boolean auth = Boolean.valueOf(authValue);

    /*
     * Conditionally create a password authenticator if the 'auth' parameter is set.
     */
    final Session mailSession = auth ? Session.getInstance(properties, new Authenticator() {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            String username = properties.getProperty("mail.smtp.user"), password = properties.getProperty("mail.smtp.password");
            return new PasswordAuthentication(username, password);
        }
    }) : Session.getInstance(properties); // without auth
    return mailSession;
}
 
Example #17
Source Project: Lottery   Author: caipiao   File: EmailSendTool.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 此段代码用来发送普通电子邮件
 * 
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 * @throws UnsupportedEncodingException
 */
public void send() throws MessagingException, UnsupportedEncodingException {
	Properties props = new Properties();
	Authenticator auth = new Email_Autherticator(); // 进行邮件服务器用户认证
	props.put("mail.smtp.host", host);
	props.put("mail.smtp.auth", "true");
	Session session = Session.getDefaultInstance(props, auth);
	// 设置session,和邮件服务器进行通讯。
	MimeMessage message = new MimeMessage(session);
	// message.setContent("foobar, "application/x-foobar"); // 设置邮件格式
	message.setSubject(mail_subject); // 设置邮件主题
	message.setText(mail_body); // 设置邮件正文
	message.setHeader(mail_head_name, mail_head_value); // 设置邮件标题

	message.setSentDate(new Date()); // 设置邮件发送日期
	Address address = new InternetAddress(mail_from, personalName);
	message.setFrom(address); // 设置邮件发送者的地址
	Address toAddress = new InternetAddress(mail_to); // 设置邮件接收方的地址
	message.addRecipient(Message.RecipientType.TO, toAddress);
	Transport.send(message); // 发送邮件
}
 
Example #18
Source Project: mnIMAPSync   Author: manusa   File: IMAPUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
@SuppressWarnings("unused")
void setUp() {
  session = mock(Session.class);
  new MockUp<Session>() {
    @Mock
    Session getInstance(Properties props, Authenticator authenticator) {
      return session;
    }
  };
  sourceIndex = mock(Index.class);
  doReturn(".").when(sourceIndex).getFolderSeparator();
  doReturn("InBox").when(sourceIndex).getInbox();
  targetIndex = mock(Index.class);
  doReturn("|").when(targetIndex).getFolderSeparator();
  doReturn("inbox").when(targetIndex).getInbox();
}
 
Example #19
Source Project: fido2   Author: StrongKey   File: EmailService.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@PostConstruct
private void init(){
    String mailhostType = Configurations.getConfigurationProperty("poc.cfg.property.mailhost.type");

    //Set mail configurations
    Properties properties = System.getProperties();
    properties.setProperty("mail.transport.protocol", "smtp");
    properties.setProperty("mail.smtp.host",
            Configurations.getConfigurationProperty("poc.cfg.property.mailhost"));
    properties.setProperty("mail.smtp.port",
            Configurations.getConfigurationProperty("poc.cfg.property.mail.smtp.port"));
    properties.setProperty("mail.smtp.from",
            Configurations.getConfigurationProperty("poc.cfg.property.smtp.from"));
    properties.setProperty("mail.smtp.auth",  String.valueOf(!mailhostType.equalsIgnoreCase("SendMail")));
    Authenticator auth = new PasswordAuthenticator(
            Configurations.getConfigurationProperty("poc.cfg.property.smtp.auth.user"),
            Configurations.getConfigurationProperty("poc.cfg.property.smtp.auth.password"));

    //TLS
    if(mailhostType.equalsIgnoreCase("StartTLS")){
        properties.setProperty("mail.smtp.starttls.enable", "true");
        session = Session.getInstance(properties, auth);
    }
    //SSL
    else if(mailhostType.equalsIgnoreCase("SSL")){
        properties.setProperty("mail.smtp.ssl.enable", "true");
        session = Session.getInstance(properties, auth);
    }
    else{
        session = Session.getInstance(properties);
    }
}
 
Example #20
Source Project: mail-micro-service   Author: hf-hf   File: MailManager.java    License: Apache License 2.0 5 votes vote down vote up
public static void putBoth(String key, Properties properties){
    putProperties(key, properties);
    // 此处要用 Session#getInstance,Session#getDefaultInstance 为单例
    Session session = Session.getInstance(properties, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(properties.getProperty("mail.username"),
                    properties.getProperty("mail.password"));
        }
    });
    if(null != properties.getProperty("mail.debug")){
        session.setDebug(Boolean.valueOf(properties.getProperty("mail.debug")));
    }
    putSession(key, session);
}
 
Example #21
Source Project: kardio   Author: tmobile   File: MailSenderUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Send Mail Alert.
 * 
 * @param Message
 */
public static void sendMail(String messageText, String toMail, String subject){
	
	Properties props = new Properties();
	props.put("mail.smtp.starttls.enable", "true");
       props.put("mail.smtp.host", propertyUtil.getValue(SurveillerConstants.MAIL_SERVER_IP));
       props.put("mail.smtp.port", propertyUtil.getValue(SurveillerConstants.MAIL_SERVER_PORT));
       Session session = null;
       String mailAuthUserName = propertyUtil.getValue(SurveillerConstants.MAIL_SERVER_USERNAME);
       String mailAuthPassword = propertyUtil.getValue(SurveillerConstants.MAIL_SERVER_PASSWORD);
	if (mailAuthUserName != null && mailAuthUserName.length() > 0 && mailAuthPassword != null
			&& mailAuthPassword.length() > 0) {
		props.put("mail.smtp.auth", "true");
		Authenticator auth = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(mailAuthUserName, mailAuthPassword);
			}
		};
		session = Session.getDefaultInstance(props, auth);
	} else {
		props.put("mail.smtp.auth", "false");
		session = Session.getInstance(props);
	}
	
	try {
		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress(propertyUtil.getValue(SurveillerConstants.MAIL_FROM_ADDRESS) ));
		message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toMail));
		message.setSubject(subject);
		message.setText(messageText);
		Transport.send(message);
	} catch (MessagingException me) {
		logger.error("Error in Mail Sending: " +  me);
		throw new RuntimeException(me.getMessage());
	}

	logger.debug("Mail Sent to: " + toMail);
}
 
Example #22
Source Project: SpringMVC-Project   Author: MartinDai   File: EmailUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 发送文本邮件
 */
public static void sendTextEmail(Authenticator authenticator, String hostName, Tuple2<String, String> fromInfo, List<Tuple2<String, String>> toList, List<Tuple2<String, String>> ccList, String subject, String textContent) throws EmailException {
    SimpleEmail simpleEmail = buildSimpleEmail(authenticator, hostName, fromInfo, toList, ccList, subject);
    simpleEmail.setMsg(textContent);

    simpleEmail.send();
}
 
Example #23
Source Project: SpringMVC-Project   Author: MartinDai   File: EmailUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 发送HTML格式邮件
 */
public static void sendHtmlEmail(Authenticator authenticator, String hostName, Tuple2<String, String> fromInfo, List<Tuple2<String, String>> toList, List<Tuple2<String, String>> ccList, String subject, String htmlContent) throws EmailException {
    HtmlEmail htmlEmail = buildHtmlEmail(authenticator, hostName, fromInfo, toList, ccList, subject);
    htmlEmail.setHtmlMsg(htmlContent);

    htmlEmail.send();
}
 
Example #24
Source Project: mail-micro-service   Author: hf-hf   File: MailManager.java    License: Apache License 2.0 5 votes vote down vote up
public static void putBoth(String key, Properties properties){
    putProperties(key, properties);
    // 此处要用 Session#getInstance,Session#getDefaultInstance 为单例
    Session session = Session.getInstance(properties, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(properties.getProperty("mail.username"),
                    properties.getProperty("mail.password"));
        }
    });
    if(null != properties.getProperty("mail.debug")){
        session.setDebug(Boolean.valueOf(properties.getProperty("mail.debug")));
    }
    putSession(key, session);
}
 
Example #25
Source Project: jweb-cms   Author: chifei   File: EmailSender.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public EmailSender(PinCodeOptions.SMTPOptions smtpOptions) {
    if (smtpOptions != null) {
        Properties properties = new Properties();
        properties.setProperty("mail.user", smtpOptions.username);
        properties.setProperty("mail.password", smtpOptions.password);
        properties.setProperty("mail.debug", "true");
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.host", smtpOptions.host);
        properties.setProperty("mail.smtp.port", String.valueOf(smtpOptions.port));
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.mime.charset", "UTF-8");
        properties.setProperty("mail.replyTo", smtpOptions.replyTo);
        if (smtpOptions.starttlsEnabled != null) {
            properties.put("mail.smtp.starttls.enable", smtpOptions.starttlsEnabled);
        }
        if (smtpOptions.sslEnabled != null) {
            properties.put("mail.smtp.ssl.enable", smtpOptions.sslEnabled);
        }
        properties.put("mail.smtp.socketFactory.port", smtpOptions.port);
        properties.put("mail.smtp.ssl.socketFactory", "javax.net.ssl.SSLSocketFactory");

        this.session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(properties.getProperty("mail.user"), properties.getProperty("mail.password"));
            }
        });
    } else {
        this.session = null;
    }
}
 
Example #26
Source Project: cosmic   Author: MissionCriticalCloud   File: ProjectManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
public EmailInvite(final String smtpHost, final int smtpPort, final boolean smtpUseAuth, final String smtpUsername, final String smtpPassword, final String emailSender,
                   final boolean smtpDebug) {
    _smtpHost = smtpHost;
    _smtpPort = smtpPort;
    _smtpUseAuth = smtpUseAuth;
    _smtpUsername = smtpUsername;
    _smtpPassword = smtpPassword;
    _emailSender = emailSender;

    if (_smtpHost != null) {
        final Properties smtpProps = new Properties();
        smtpProps.put("mail.smtp.host", smtpHost);
        smtpProps.put("mail.smtp.port", smtpPort);
        smtpProps.put("mail.smtp.auth", "" + smtpUseAuth);
        if (smtpUsername != null) {
            smtpProps.put("mail.smtp.user", smtpUsername);
        }

        smtpProps.put("mail.smtps.host", smtpHost);
        smtpProps.put("mail.smtps.port", smtpPort);
        smtpProps.put("mail.smtps.auth", "" + smtpUseAuth);
        if (smtpUsername != null) {
            smtpProps.put("mail.smtps.user", smtpUsername);
        }

        if ((smtpUsername != null) && (smtpPassword != null)) {
            _smtpSession = Session.getInstance(smtpProps, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(smtpUsername, smtpPassword);
                }
            });
        } else {
            _smtpSession = Session.getInstance(smtpProps);
        }
        _smtpSession.setDebug(smtpDebug);
    } else {
        _smtpSession = null;
    }
}
 
Example #27
Source Project: journaldev   Author: journaldev   File: SSLEmail.java    License: MIT License 5 votes vote down vote up
/**
   Outgoing Mail (SMTP) Server
   requires TLS or SSL: smtp.gmail.com (use authentication)
   Use Authentication: Yes
   Port for SSL: 465
 */
public static void main(String[] args) {
	final String fromEmail = "[email protected]";
	final String password = "my_pwd";
	final String toEmail = "[email protected]";
	
	System.out.println("SSLEmail Start");
	Properties props = new Properties();
	props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
	props.put("mail.smtp.socketFactory.port", "465"); //SSL Port
	props.put("mail.smtp.socketFactory.class",
			"javax.net.ssl.SSLSocketFactory"); //SSL Factory Class
	props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
	props.put("mail.smtp.port", "465"); //SMTP Port
	
	Authenticator auth = new Authenticator() {
		//override the getPasswordAuthentication method
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(fromEmail, password);
		}
	};
	
	Session session = Session.getDefaultInstance(props, auth);
	System.out.println("Session created");
    EmailUtil.sendEmail(session, toEmail,"SSLEmail Testing Subject", "SSLEmail Testing Body");

    EmailUtil.sendAttachmentEmail(session, toEmail,"SSLEmail Testing Subject with Attachment", "SSLEmail Testing Body with Attachment");

    EmailUtil.sendImageEmail(session, toEmail,"SSLEmail Testing Subject with Image", "SSLEmail Testing Body with Image");

}
 
Example #28
Source Project: IBMonitorService   Author: UMN-PeopleSoft   File: Monitor.java    License: GNU General Public License v3.0 5 votes vote down vote up
private Session createSession() {
	Properties props = new Properties();
	if (IBMonitorSvc.emailUser.isEmpty() || IBMonitorSvc.emailUser.equals("")) {
		props.setProperty("mail.smtp.host", IBMonitorSvc.emailHost);
		props.setProperty("mail.smtp.port", String.valueOf(IBMonitorSvc.emailPort));
		props.setProperty("mail.smtp.auth", "false");
		props.setProperty("mail.transport.protocol", "smtp");
		if (IBMonitorSvc.emailPort == 25) {
			props.setProperty("mail.smtp.starttls.enable","false"); //Important: must start TLS
		} else {
			props.setProperty("mail.smtp.starttls.enable","true"); //Important: must start TLS
		}
	} else {
		props.setProperty("mail.smtp.host", IBMonitorSvc.emailHost);
		props.setProperty("mail.smtp.port", String.valueOf(IBMonitorSvc.emailPort));
		props.setProperty("mail.smtp.auth", "true");
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.smtp.starttls.enable","true"); //Important: must start TLS
	}

	Authenticator auth = new SMTPAuthenticator();
	Session session = Session.getInstance(props, auth);
	session.setDebug(false);
	
	return session;

}
 
Example #29
Source Project: baleen   Author: dstl   File: EmailReader.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doInitialize(UimaContext context) throws ResourceInitializationException {
  validateParams();

  Authenticator authenticator =
      new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication(user, pass);
        }
      };

  Properties prop = new Properties();
  prop.put("mail.store.protocol", protocol);
  prop.put("mail.host", server);
  prop.put("mail." + protocol + ".port", port);
  prop.put("mail.user", user);

  Session session = Session.getInstance(prop, authenticator);
  try {
    store = session.getStore();
  } catch (NoSuchProviderException e) {
    throw new ResourceInitializationException(e);
  }

  try {
    store.connect();
    inboxFolder = store.getFolder(inbox);
    reopenConnection();
  } catch (MessagingException me) {
    throw new ResourceInitializationException(me);
  }
}
 
Example #30
Source Project: che   Author: eclipse   File: MailSessionProvider.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@VisibleForTesting
MailSessionProvider(Map<String, String> mailConfiguration) {
  if (mailConfiguration != null && !mailConfiguration.isEmpty()) {
    Properties props = new Properties();
    mailConfiguration.forEach(props::setProperty);

    if (Boolean.parseBoolean(props.getProperty("mail.smtp.auth"))) {
      final String username = props.getProperty("mail.smtp.auth.username");
      final String password = props.getProperty("mail.smtp.auth.password");

      // remove useless properties
      props.remove("mail.smtp.auth.username");
      props.remove("mail.smtp.auth.password");

      this.session =
          Session.getInstance(
              props,
              new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(username, password);
                }
              });
    } else {
      this.session = Session.getInstance(props);
    }
  } else {
    LOG.warn("Mail server is not configured. Cannot send emails.");
    this.session = null;
  }
}