简单 java mail 在 jsp 中发送邮件

时间:2022-12-30 16:19:27

<%@page language="java" contentType="text/html; charset=gbk"
    pageEncoding="gbk"%>
<%@page import="javax.mail.*,javax.mail.internet.*,javax.activation.*,java.util.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html; charset=GBK">


  <html>

  <head>

   <TITLE>JavaMail 电子邮件发送系统</TITLE>

  </HEAD>

  <BODY>
  <%

 String from = "xiaogeasd@sina.com";
        String to = "xiaogeasd@sina.com";
        String subject = "Test mail";
        String body = "A text mail";
        Properties props = System.getProperties();
        // 设置SMTP邮件服务器:
        props.put("mail.smtp.host", "smtp.sina.com");
        // SMTP服务器需要验证:
        props.put("mail.smtp.auth", "true");
        // 传入用户名和口令:
        Session session1 = Session.getInstance(props,null);
        // 创建新邮件:
        Message msg = new MimeMessage(session1);
        msg.setFrom(new InternetAddress(from));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        msg.setSubject(subject);
        msg.setText(body);
        msg.setSentDate(new Date());
        Transport transport = session1.getTransport("smtp");       
        // 发送:
        transport.connect("smtp.sina.com", "用户名", "密码");
  transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
 %>

  </body>

  </HTML>