Bha*_*esh 2 java email servlets
我们正在JSF中开发一个简单的Web应用程序,其中需要包含"忘记密码"模块.为了演示和简单起见,我在Java Servlet中尝试了以下代码.它可以向Gmail发送邮件,并且可以正常工作,完全没有问题.以下是完整的Servlet代码.
public class MailClient extends HttpServlet {
private class SMTPAuthenticator extends Authenticator {
private PasswordAuthentication authentication;
public SMTPAuthenticator(String login, String password) {
authentication = new PasswordAuthentication(login, password);
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
}
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String from = "bhaveshp1980@gmail.com";
String to = "bhaveshp1980@gmail.com";
String subject = "A mail from Java.";
String message = "My first mail from Java.";
String login = "bhaveshp1980@gmail.com";
String password = "password";
Properties props = new Properties();
props.setProperty("mail.host", "smtp.gmail.com");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable", "true");
Authenticator auth = new SMTPAuthenticator(login, password);
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
try {
msg.setText(message);
msg.setSubject(subject);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
Transport.send(msg);
} catch (MessagingException ex) {
Logger.getLogger(MailClient.class.getName()).
log(Level.SEVERE, null, ex);
}
} finally {
out.close();
}
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}
}
Run Code Online (Sandbox Code Playgroud)
现在,第一个问题是,一旦用户输入其有效的电子邮件地址,就应该将验证码提交给特定的消息服务器(Gmail,Yahoo等)而不要求用户输入密码(事实并非如此)上面的代码),这对于在Web应用程序中实现"忘记密码"模块是必不可少的.
的第二个问题是,上述代码被绑定到发送邮件只到Gmail.如果我想发送邮件到其他一些消息服务器说雅虎,声明
props.setProperty("mail.host", "smtp.gmail.com");
Run Code Online (Sandbox Code Playgroud)
需要改为
props.setProperty("mail.host", "smtp.mail.yahoo.com");
Run Code Online (Sandbox Code Playgroud)
[并且端口也没有,关于其他人]意味着需要正确识别必须向其发送消息的特定消息服务器.这是最好的方法吗?请解决这些问题的最佳方法是什么.
每次向其他邮件提供商发送邮件时,是否更改了电子邮件客户端中的SMTP设置?不可以.将邮件发送到gmail.com地址时,不要将SMTP服务器设置为gmail.然后在将邮件发送到yahoo.com地址时将其设置为yahoo.您将其设置为您的电子邮件提供商SMTP服务器,此SMTP服务器将邮件发送到适当的位置.
只需选择一个同意从您的应用程序发送邮件的SMTP服务器.任何SMTP提供商都可以每天发送十几个.但是,如果您每天发送数千个,那么您的提供商可能会遇到问题.只需询问您的托管服务提供商如何处理外发邮件(费用是多少,每天接受多少,是否有带宽限制等)
归档时间: |
|
查看次数: |
1641 次 |
最近记录: |