有我的档案:
的index.html
<form action="servlet/SendMail">
To:<input type="text" name="to"/><br/>
Subject:<input type="text" name="subject"><br/>
Text:<textarea rows="10" cols="70" name="msg"></textarea><br/>
<input type="submit" value="send">
</form>
SendMail.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SendMail extends javax.servlet.http.HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String to=request.getParameter("to");
String subject=request.getParameter("subject");
String msg=request.getParameter("msg");
Mailer.send(to, subject, msg);
out.print("message has been sent successfully");
out.close();
}
}
Mailer.java
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Mailer {
public static void send(String to,String subject,String msg){
final String user="myid@gmail.com";
final String pass="*********";
Properties props = new Properties();
props.setProperty("mail.smtp.port", "465");
props.put("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty("mail.smtp.auth", "true");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,pass);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject(subject);
message.setText(msg);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}