javax.mail.PasswordAuthentication Java Examples

The following examples show how to use javax.mail.PasswordAuthentication. 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: 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 #4
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 #5
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 #6
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 #7
Source File: Email.java    From OpenSZZ-Cloud-Native with GNU General Public License v3.0 6 votes vote down vote up
public Email(String emailTo, String token, String projectName, String urlWebService){
	this.emailTo = emailTo;
	this.projectName = projectName;
	this.token = token;
	this.urlWebService = urlWebService;
	

	props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");
      
    session = Session.getInstance(props,
  		  new javax.mail.Authenticator() {
  			protected PasswordAuthentication getPasswordAuthentication() {
  				return new PasswordAuthentication(username, password);
  			}
  		  });
	
}
 
Example #8
Source File: Email.java    From OpenSZZ-Cloud-Native with GNU General Public License v3.0 6 votes vote down vote up
public Email(String emailTo, String token, String projectName, String urlWebService){
	this.emailTo = emailTo;
	this.projectName = projectName;
	this.token = token;
	this.urlWebService = urlWebService;
	
	props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");
    
    session = Session.getInstance(props,
  		  new javax.mail.Authenticator() {
  			protected PasswordAuthentication getPasswordAuthentication() {
  				return new PasswordAuthentication(username, password);
  			}
  		  });
	
}
 
Example #9
Source File: ManagedPasswordAuthenticator.java    From kumuluzee with MIT License 6 votes vote down vote up
@Override
protected PasswordAuthentication getPasswordAuthentication() {

    String protocol = getRequestingProtocol();

    MailServiceConfig requestingConfig = null;

    if (mailSessionConfig.getTransport() != null && protocol.equals(mailSessionConfig.getTransport().getProtocol())) {
        requestingConfig = mailSessionConfig.getTransport();
    } else if (mailSessionConfig.getStore() != null && protocol.equals(mailSessionConfig.getStore().getProtocol())) {
        requestingConfig = mailSessionConfig.getStore();
    }

    if (requestingConfig != null && requestingConfig.getPassword() != null) {

        return new PasswordAuthentication(requestingConfig.getUsername(), requestingConfig.getPassword());
    }

    return null;
}
 
Example #10
Source File: SendEmailToUser.java    From Hotel-Properties-Management-System with GNU General Public License v2.0 6 votes vote down vote up
public void setReadyForEmail(String username, String password) {
	props = new Properties();
	props.put("mail.smtp.host", "smtp.gmail.com");
	props.put("mail.smtp.socketFactory.port", "465");
	props.put("mail.smtp.socketFactory.class",
			"javax.net.ssl.SSLSocketFactory");
	props.put("mail.smtp.auth", "true");
	props.put("mail.smtp.port", "465");
	
	Session session = Session.getDefaultInstance(props,
			new javax.mail.Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(username, password);
				}
			});
	
	message = new MimeMessage(session);
}
 
Example #11
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 #12
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 #13
Source File: Mailer.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
private static void sendMail()
        throws MessagingException, IOException {
    Session session = Session.getInstance(getMailProps(), new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(
                    getVal("username"),
                    getVal("password"));
        }
    });
    session.setDebug(getBoolVal("mail.debug"));
    LOG.info("Compiling Mail before Sending");
    Message message = createMessage(session);
    Transport transport = session.getTransport("smtp");
    LOG.info("Connecting to Mail Server");
    transport.connect();
    LOG.info("Sending Mail");
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
    LOG.info("Reports are sent to Mail");
    clearTempZips();
}
 
Example #14
Source File: SendMail.java    From PatatiumWebUi with Apache License 2.0 6 votes vote down vote up
public PasswordAuthentication passwordAuthentication()
{
	String userName=getDefaultUserName();
	//当前用户在密码表里
	if (pwdProperties.containsKey(userName)) {
		//取出密码,封装好后返回
		return new PasswordAuthentication(userName, pwdProperties.getProperty(userName).toString());

	}
	else {
		//如果当前用户不在密码表里就返回Null
		System.out.println("当前用户不存在");
		return null;


	}

}
 
Example #15
Source File: MailNotification.java    From play-with-hexagonal-architecture with Do What The F*ck You Want To Public License 6 votes vote down vote up
public MailNotification(final String username, final String password) {

        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");

        this.session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });
    }
 
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: GMailClient.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
GMailClient(MailProperties mailProperties) {
    String username = mailProperties.getSMTPUsername();
    String password = mailProperties.getSMTPPassword();

    log.info("Initializing gmail smtp mail transport. Username : {}. SMTP host : {}:{}",
            username, mailProperties.getSMTPHost(), mailProperties.getSMTPort());

    this.session = Session.getInstance(mailProperties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
    try {
        this.from = new InternetAddress(username);
    } catch (AddressException e) {
        throw new RuntimeException("Error initializing MailWrapper." + e.getMessage());
    }
}
 
Example #19
Source File: MailSessionProvider.java    From che with 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;
  }
}
 
Example #20
Source File: Email.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public Session connectSession() {			 
	Properties props = new Properties();
	Session session = null;
	if (isSSLRequired()) {
		props.put("mail.smtp.host", getOutgoingHost());
		props.put("mail.smtp.port", getOutgoingPort());
		props.put("mail.smtp.socketFactory.port", getOutgoingPort());
		props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.ssl.trust", getOutgoingHost());
		 
		session = Session.getInstance(props, new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(getUsername(), getPassword());
			}
		});
	} else {
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", getOutgoingHost());
		props.put("mail.smtp.port", getOutgoingPort());
		props.put("mail.smtp.ssl.trust", getOutgoingHost());
		 
		session = Session.getInstance(props, new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(getUsername(), getPassword());
			}
		});
	}
	return session;
}
 
Example #21
Source File: CustomerMasterService.java    From jVoiD with Apache License 2.0 5 votes vote down vote up
public void sendEmail(String email, String password){
	
	Properties properties = System.getProperties();
	properties.put("mail.smtp.starttls.enable", "true");
	properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.auth", false);
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.port", 587);
    Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication("[email protected]", "test123");
		}
    });
    
    try {
    	 
		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress("[email protected]"));
		message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
		message.setSubject("Reset Password");
		String content = "Your new password is " + password;
		message.setText(content);
			Transport.send(message);

	} catch (MessagingException e) {
		throw new RuntimeException(e);
	}
}
 
Example #22
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 #23
Source File: EmailUtil.java    From Library-Assistant with Apache License 2.0 5 votes vote down vote up
public static void sendMail(MailServerInfo mailServerInfo, String recepient, String content, String title, GenericCallback callback) {

        Runnable emailSendTask = () -> {
            LOGGER.log(Level.INFO, "Initiating email sending task. Sending to {}", recepient);
            Properties props = new Properties();
            try {
                MailSSLSocketFactory sf = new MailSSLSocketFactory();
                sf.setTrustAllHosts(true);
                props.put("mail.imap.ssl.trust", "*");
                props.put("mail.imap.ssl.socketFactory", sf);
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.starttls.enable", mailServerInfo.getSslEnabled() ? "true" : "false");
                props.put("mail.smtp.host", mailServerInfo.getMailServer());
                props.put("mail.smtp.port", mailServerInfo.getPort());

                Session session = Session.getInstance(props, new javax.mail.Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(mailServerInfo.getEmailID(), mailServerInfo.getPassword());
                    }
                });

                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(mailServerInfo.getEmailID()));
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recepient));
                message.setSubject(title);
                message.setContent(content, "text/html");

                Transport.send(message);
                LOGGER.log(Level.INFO, "Everything seems fine");
                callback.taskCompleted(Boolean.TRUE);
            } catch (Throwable exp) {
                LOGGER.log(Level.INFO, "Error occurred during sending email", exp);
                callback.taskCompleted(Boolean.FALSE);
            }
        };
        Thread mailSender = new Thread(emailSendTask, "EMAIL-SENDER");
        mailSender.start();
    }
 
Example #24
Source File: TestConfig.java    From chronos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Bean
public Session authSession() {
  final String username = "spluh";
  final String password = "abracaduh";
  Session session = Session.getInstance(authMailProperties(), new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(username, password);
    }
  });
  return session;
}
 
Example #25
Source File: MailSenderUtil.java    From kardio with 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 #26
Source File: SSLEmail.java    From journaldev with 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 #27
Source File: MailManager.java    From mail-micro-service with 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 #28
Source File: ProjectManagerImpl.java    From cosmic with 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 #29
Source File: MailSender.java    From SMS302 with Apache License 2.0 5 votes vote down vote up
boolean send(String title, String body, String toAddr) {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", HOST);
    props.put("mail.smtp.port", PORT);

    Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(USER_NAME, PASSWORD);
                }
            });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(USER_NAME));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(toAddr));
        message.setSubject(title);
        message.setText(body);

        Transport.send(message);

        System.out.println("Mail sent.");
        return true;

    } catch (MessagingException e) {
        e.printStackTrace();
    }
    return false;
}
 
Example #30
Source File: MailManager.java    From mail-micro-service with 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);
}