下面列出了怎么用javax.mail.PasswordAuthentication的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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;
}
/**
* 创建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;
}
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();
}
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);
}
});
}
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);
}
});
}
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;
}
/**
* 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;
}
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);
}
/**
* 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);
}
}
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;
}
}
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();
}
@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;
}
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;
}
}
/**
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");
}
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);
}
});
}
/**
* 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);
}
});
}
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();
}
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());
}
}
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);
}
/**
* 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);
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
String username = ApplicationConstants.USERNAME_FOR_SMTP;
String password = ApplicationConstants.PASSWORD_FOR_SMTP;
if ((username != null) && (username.length() > 0) && (password != null)
&& (password.length() > 0)) {
return new PasswordAuthentication(username, password);
}
return null;
}
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);
}
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;
}
}
public static void main(String[] args) {
Properties props = new Properties();
/** Parâmetros de conexão com servidor Gmail */
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() {
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("[email protected]", "tjm123456");
}
});
/** Ativa Debug para sessão */
session.setDebug(true);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]")); //Remetente
Address[] toUser = InternetAddress //Destinatário(s)
.parse("[email protected]");
message.setRecipients(Message.RecipientType.TO, toUser);
message.setSubject("Enviando email com JavaMail");//Assunto
message.setText("Enviei este email utilizando JavaMail com minha conta GMail!");
/**Método para enviar a mensagem criada*/
Transport.send(message);
System.out.println("Feito!!!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
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;
}
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;
}
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;
}
}
public Session connectSession() {
Properties props = new Properties();
Session session = null;
if (ssl) {
props.put("mail.smtp.host", this.outgoingHost);
props.put("mail.smtp.port", this.outgoingPort);
props.put("mail.smtp.socketFactory.port", this.outgoingPort);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.trust", this.outgoingHost);
session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
} else {
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", this.outgoingHost);
props.put("mail.smtp.port", this.outgoingPort);
props.put("mail.smtp.ssl.trust", this.outgoingHost);
session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
return session;
}
/**
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");
}
@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;
}