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 File: TLSEmail.java    From journaldev with 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 File: MailDaemon.java    From Open-Lowcode with Eclipse Public License 2.0 7 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 File: ErrorMail.java    From mzmine3 with 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 #4
Source File: SmartSendMailUtil.java    From smart-admin with 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 #5
Source File: EmailSender.java    From personal_book_library_web_project with 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 File: IMAPUtilsTest.java    From mnIMAPSync with 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 #7
Source File: EmailNotificationService.java    From localization_nifi with 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 File: EmailSendTool.java    From Lottery with 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 #9
Source File: UsernamePasswordAuthenticatorBuilder.java    From ogham with 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 #10
Source File: PutEmail.java    From localization_nifi with 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 #11
Source File: EmailTask.java    From jivejdon with 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 #12
Source File: EmailApp.java    From phoebus with 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 #13
Source File: JavaMail.java    From EasyML with 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 #14
Source File: PutEmail.java    From nifi with 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 #15
Source File: EmailNotificationService.java    From nifi with 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 File: PortalTester.java    From development with 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 #17
Source File: ErrorMail.java    From mzmine2 with 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 #18
Source File: EagleMailClient.java    From Eagle with 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 #19
Source File: EmailService.java    From fido2 with 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 File: MailReceiver.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 创建 Session
 */
private void createSession() {
	session = Session.getInstance(props, new Authenticator() {
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(userName, password);
		}
	});
}
 
Example #21
Source File: EmailSender.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private Session createSession() {
  Session session;
  if (!auth) {
    session = Session.getInstance(javaMailProps);
  } else {
    session = Session.getInstance(javaMailProps, new Authenticator() {
      @Override
      protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password);
      }
    });
  }
  return session;
}
 
Example #22
Source File: ExceptionNotificationServiceImpl.java    From telekom-workflow-engine with MIT License 5 votes vote down vote up
private void sendEmail( String from, String to, String subject, String body ){
    log.info( "Sending exception email from:{} to:{} subject:{}", from, to, subject );
    try{
        Properties props = new Properties();
        props.put( "mail.smtp.host", smtpHost );
        if (StringUtils.isNotBlank(smtpPort)) {
            props.put( "mail.smtp.port", smtpPort );
        }
        Authenticator authenticator = null;
        if (StringUtils.isNotBlank(smtpUsername)) {
            props.put( "mail.smtp.auth", true );
            authenticator = new SmtpAuthenticator();
        }
        Session session = Session.getDefaultInstance( props, authenticator );

        Message msg = new MimeMessage( session );
        msg.setFrom( new InternetAddress( from ) );

        InternetAddress[] addresses = InternetAddress.parse( to );
        msg.setRecipients( Message.RecipientType.TO, addresses );

        msg.setSubject( subject );
        msg.setSentDate( new Date() );
        msg.setText( body );
        Transport.send( msg );
    }
    catch( Exception e ){
        log.warn( "Sending email failed: ", e );
    }
}
 
Example #23
Source File: EmailService.java    From tomee with Apache License 2.0 5 votes vote down vote up
@POST
public String lowerCase(final String message) {

    try {

        //Create some properties and get the default Session
        final Properties props = new Properties();
        props.put("mail.smtp.host", "your.mailserver.host");
        props.put("mail.debug", "true");

        final Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("MyUsername", "MyPassword");
            }
        });

        //Set this just to see some internal logging
        session.setDebug(true);

        //Create a message
        final MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("[email protected]"));
        final InternetAddress[] address = {new InternetAddress("[email protected]")};
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject("JavaMail API test");
        msg.setSentDate(new Date());
        msg.setText(message, "UTF-8");


        Transport.send(msg);
    } catch (final MessagingException e) {
        return "Failed to send message: " + e.getMessage();
    }

    return "Sent";
}
 
Example #24
Source File: EmailPlugin.java    From hawkular-alerts with Apache License 2.0 5 votes vote down vote up
private void initMailSession(ActionMessage msg) {
    boolean offLine = System.getProperty(MAIL_SESSION_OFFLINE) != null;
    if (!offLine) {
        Properties emailProperties = new Properties();
        msg.getAction().getProperties().entrySet().stream()
                .filter(e -> e.getKey().startsWith("mail."))
                .forEach(e -> {
                    emailProperties.put(e.getKey(), e.getValue());
                });
        Properties systemProperties = System.getProperties();
        for (String property : systemProperties.stringPropertyNames()) {
            if (property.startsWith("mail.")) {
                emailProperties.putIfAbsent(property, System.getProperty(property));
            }
        }
        emailProperties.putIfAbsent("mail.smtp.host", DEFAULT_MAIL_SMTP_HOST);
        emailProperties.putIfAbsent("mail.smtp.port", DEFAULT_MAIL_SMTP_PORT);
        if (emailProperties.containsKey("mail.smtp.user")
                && emailProperties.containsKey("mail.smtp.pass")) {
            String user = emailProperties.getProperty("mail.smtp.user");
            String password = emailProperties.getProperty("mail.smtp.pass");
            mailSession = Session.getInstance(emailProperties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(user, password);
                }
            });
        } else {
            mailSession = Session.getInstance(emailProperties);
        }
    }
}
 
Example #25
Source File: SmtpOutputOperator.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
private void reset()
{
  if (!setupCalled) {
    return;
  }
  if (!StringUtils.isBlank(smtpPassword)) {
    properties.setProperty("mail.smtp.auth", "true");
    properties.setProperty("mail.smtp.starttls.enable", "true");
    if (useSsl) {
      properties.setProperty("mail.smtp.socketFactory.port", String.valueOf(smtpPort));
      properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      properties.setProperty("mail.smtp.socketFactory.fallback", "false");
    }

    auth = new Authenticator()
    {
      @Override
      protected PasswordAuthentication getPasswordAuthentication()
      {
        return new PasswordAuthentication(smtpUserName, smtpPassword);
      }

    };
  }

  properties.setProperty("mail.smtp.host", smtpHost);
  properties.setProperty("mail.smtp.port", String.valueOf(smtpPort));
  session = Session.getInstance(properties, auth);
  resetMessage();
}
 
Example #26
Source File: SmtpExecutor.java    From Thunder with Apache License 2.0 5 votes vote down vote up
protected Session createSession() {
    Properties properties = createProperties();
    Authenticator authenticator = createAuthenticator();

    Session session = Session.getDefaultInstance(properties, authenticator);

    return session;
}
 
Example #27
Source File: SmtpExecutor.java    From Thunder with Apache License 2.0 5 votes vote down vote up
protected Authenticator createAuthenticator() {
    return new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, password);
        }
    };
}
 
Example #28
Source File: EmailNotificationPluginImplUnitTest.java    From email-notifier with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);

    when(mockSession.getTransport()).thenReturn(mockTransport);

    when(mockSessionFactory.getInstance(any(Properties.class))).thenReturn(mockSession);
    when(mockSessionFactory.getInstance(any(Properties.class), any(Authenticator.class))).thenReturn(mockSession);

    emailNotificationPlugin = new EmailNotificationPluginImpl();
    emailNotificationPlugin.initializeGoApplicationAccessor(goApplicationAccessor);
    emailNotificationPlugin.setSessionFactory(mockSessionFactory);
}
 
Example #29
Source File: SmtpManager.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Authenticator buildAuthenticator(final String username, final String password) {
    if (null != password && null != username) {
        return new Authenticator() {
            private final PasswordAuthentication passwordAuthentication =
                new PasswordAuthentication(username, password);

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return passwordAuthentication;
            }
        };
    }
    return null;
}
 
Example #30
Source File: EmailSender.java    From core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Reads config properties from config file and creates a session that can
 * be used to send e-mails.
 */
public EmailSender() {
	// Set user and password and returns session that can be used to
	// send a message.
	Properties props = getProperties();
	final String user = props.getProperty("mail.smtp.user");
	final String password = props.getProperty("mail.smtp.password");
	Authenticator authenticator = new Authenticator() {
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(user, password);
		}
	};
	
	session = Session.getDefaultInstance(props, authenticator);
}