这是我的状态我在应用程序中使用我们公司的电子邮件和密码验证用户
我创建了一个类来处理身份验证操作,我需要保留我session
的引用才能发送电子邮件。
我的尝试:
1-保存用户名,密码,这不安全。
2-通过应用程序实例保存会话,但在应用关闭时删除。
任何建议都要提前感谢
import javax.activation.DataHandler;
import javax.mail.AuthenticationFailedException;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;
/**
* Created by mina on 8/28/2016.
*/
public class PMailSender {
private String username;
private String password;
private String mailhost = "OURHOSt";
private String stmp_port= "465";
private Session session;
static {
Security.addProvider(new JSSEProvider());
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public PMailSender(){
}
public PMailSender(String username, String password) {
this.username = username;
this.password = password;
Properties prop = new Properties();
prop.setProperty("mail.transport.protocol" , "smtp");
prop.setProperty("mail.host" , mailhost);
prop.setProperty("mail.smtp.quitwait" , "false");
prop.put("mail.smtp.auth" , "true");
prop.put("mail.smtp.port" , stmp_port);
prop.put("mail.smtp.socketFactory.port" , stmp_port);
prop.put("mail.smtp.socketFactory.class" , "javax.net.ssl.SSLSocketFactory");
prop.put("mail.smtp.socketFactory.fallback","false");
session = Session.getInstance(prop , new PMailAuthenticator(username,password ));
session.setDebug(true);
}
public boolean ValidateCredential(){
try {
Transport tr= session.getTransport();
tr.connect(mailhost , username , password);
Store mStore=session.getStore();
tr.close();
}catch (AuthenticationFailedException e){
return false;
}catch (MessagingException e){
throw new RuntimeException("validate error " , e);
}
return true;
}
public synchronized void SendMail (String subject , String body
, String sender , String recipients ) throws MessagingException {
MimeMessage message = new MimeMessage(session);
DataHandler handler= new DataHandler(new ByteArrayDataSource(body.getBytes() , "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if(recipients.indexOf(",") > 0)
message.setRecipients(Message.RecipientType.TO ,InternetAddress.parse(recipients) );
else
message.setRecipient(Message.RecipientType.TO , new InternetAddress(recipients));
Transport.send(message);
}
}