如果你重新学习如何通过 Java寄邮件,尝试其他方式,那么,你需要把邮件送给你的电子邮件提供者员工和管理当局协调会服务器,而这一员工和管理当局协调会服务器则将邮件送至与本守则无关的适当地点。
<>0> 该守则在Java 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 = "xyz.com";
String to = "abc.com";
String subject = "Your Subject.";
String message = "Message Text.";
String login = "xyz.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";
}
}