📄 mailservlet.java~38~
字号:
package mail;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.Message.RecipientType;
import javax.mail.internet.MimeMessage;
import javax.mail.Session;
import javax.mail.MessagingException;
public class MailServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GB18030";
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType(CONTENT_TYPE) ;
PrintWriter out = response.getWriter() ;
String host = "smtp.sina.com"; //发件人使用发邮件的电子信箱服务器
String from = "javamail9930@sina.com"; //发邮件的出发地(发件人的信箱)
String to = "javamail9930@126.com"; //发邮件的目的地(收件人信箱)
try
{
// Get system properties
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", host);
// Get session
props.put("mail.smtp.auth", "true"); //这样才能通过验证
MyAuthenticator myauth = new MyAuthenticator("javamail9930@sina.com",
"123456");
Session session = Session.getDefaultInstance(props, myauth);
// session.setDebug(true);
// Define message
MimeMessage message = new MimeMessage(session);
// Set the from address
message.setFrom(new InternetAddress(from));
// Set the to address
message.addRecipient(RecipientType.TO,
new InternetAddress(to));
// Set the subject
message.setSubject("第一个测试程序!");
// Set the content
message.setText("这是用java写的发送电子邮件的测试程序!");
message.saveChanges();
Transport.send(message);
out.print("发送成功") ;
}
catch(Exception e)
{
System.out.println(e) ;
}
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
try {
doGet(request, response);
}catch (Exception ex)
{
System.out.println(ex) ;
}
}
//Clean up resources
public void destroy() {
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -