JAVA送信メール

2753 ワード

これは私がメールを送信するコードを使ったことがあります.中には注釈が詳しく書かれています.一部のパラメータは、自分のメールサーバアドレスに基づいて構成されます.
<%@ page contentType="text/html;charset=GB2312" %>
<!--        -->
<%@ page import="java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*"%>
<%!
public String codeToString(String str)
{//          
  String s=str;
  try
    {
    byte tempB[]=s.getBytes("ISO-8859-1");
    s=new String(tempB);
    return s;
   }
  catch(Exception e)
   {
    return s;
   }  
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>       </title>
</head>
<body>
<%
try{
// html         
String to_mail=codeToString(request.getParameter("to"));
String to_title=codeToString(request.getParameter("title"));
String to_content=codeToString(request.getParameter("content"));

to_mail = "[email protected]";//    
to_title = "test";
to_content = "<table border='1' bgColor='red'><tr><td>      </td></tr></table>";

//      
Properties props=new Properties();//   Properties props = System.getProperties(); 
props.put("mail.smtp.host","xxxxx.com");//            
props.put("mail.smtp.auth","true");//      
Session s=Session.getInstance(props);//            
s.setDebug(true);

//             
MimeMessage message=new MimeMessage(s);//             

//    
InternetAddress from=new InternetAddress("[email protected]");//        
message.setFrom(from);//     
InternetAddress to=new InternetAddress(to_mail);
message.setRecipient(Message.RecipientType.TO,to);//     ,         TO
message.setSubject(to_title);//    
message.setText(to_content);//      
message.setSentDate(new Date());//      

 BodyPart mdp=new MimeBodyPart();//           BodyPart  
  mdp.setContent(to_content,"text/html;charset=gb2312");// BodyPart         /    
  Multipart mm=new MimeMultipart();//    MimeMultipart      BodyPart 
//           

  mm.addBodyPart(mdp);// BodyPart   MimeMultipart   (      BodyPart)
  message.setContent(mm);// mm         




//    
message.saveChanges();//      
Transport transport=s.getTransport("smtp");
// smtp      ,                 SMTP  ,         ,        
transport.connect("192.168.0.1","user","password");
transport.sendMessage(message,message.getAllRecipients());//    ,                   
transport.close();
%>
<div align="center">
<p>    !</p>
</div>
<%
}catch(MessagingException e){
out.println("    !");
}
%>
</body>
</html>