Если вы только учитесь отправлять почту через Java, попробуйте следующее, в противном случае вам нужно будет установить его на SMTP-сервер вашего почтового провайдера, а этот SMTP-сервер, в свою очередь, отправит почту в соответствующее местоположение, которое не является случай с этим кодом.
ПРИМЕЧАНИЕ: Код написан на сервлете Java.
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";
}
}