***** 教材示例 ********* /* * Copyright (c) 2000 David Flanagan. All rights reserved. * This code is from the book Java Examples in a Nutshell, 2nd Edition. * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied. * You may study, use, and modify it for any non-commercial purpose. * You may distribute it non-commercially as long as you retain this notice. * For a commercial use license, or to purchase the book (recommended), * visit http://www.davidflanagan.com/javaexamples2. */ package com.davidflanagan.examples.net; import java.io.*; import java.net.*;/** * This program sends e-mail using a mailto: URL **/ public class SendMail { public static void main(String[] args) { try { // If the user specified a mailhost, tell the system about it. if (args.length >= 1) System.getProperties().put("mail.host", args[0]);
// A Reader stream to read from the console BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Ask the user for the from, to, and subject lines System.out.print("From: "); String from = in.readLine(); System.out.print("To: "); String to = in.readLine(); System.out.print("Subject: "); String subject = in.readLine();
// Establish a network connection for sending mail URL u = new URL("mailto:" + to); // Create a mailto: URL URLConnection c = u.openConnection(); // Create its URLConnection c.setDoInput(false); // Specify no input from it c.setDoOutput(true); // Specify we'll do output System.out.println("Connecting..."); // Tell the user System.out.flush(); // Tell them right now c.connect(); // Connect to mail host PrintWriter out = // Get output stream to host new PrintWriter(new OutputStreamWriter(c.getOutputStream())); // Write out mail headers. Don't let users fake the From address out.print("From: \"" + from + "\" <" + System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName() + ">\n"); out.print("To: " + to + "\n"); out.print("Subject: " + subject + "\n"); out.print("\n"); // blank line to end the list of headers // Now ask the user to enter the body of the message System.out.println("Enter the message. " + "End with a '.' on a line by itself."); // Read message line by line and send it out. String line; for(;;) { line = in.readLine(); if ((line == null) || line.equals(".")) break; out.print(line + "\n"); }
// Close (and flush) the stream to terminate the message out.close(); // Tell the user it was successfully sent. System.out.println("Message sent."); } catch (Exception e) { // Handle any exceptions, print error message. System.err.println(e); System.err.println("Usage: java SendMail [<mailhost>]"); } } }
<head>发送电子邮件</head>
<%@page contentType="text/html; charset=gb2312"%>
<%@ page import="java.io.*,java.net.*,java.util.*,java.text.*"%>
<%!
class Parameters
{
JspWriter out;
Socket socket;
PrintWriter mailout;
BufferedReader mailIn;
}
void sendCommand(Parameters parms,String cmd) throws IOException
{
parms.out.println("C: "+cmd);
parms.mailout.print(cmd+"\r\n");
parms.mailout.flush();
String line=parms.mailIn.readLine();
parms.out.println("S: "+line);
}
void sendData(Parameters parms,String from,String to,String subject,String message) throws IOException
{
String mes="";
String End="\r\n";
String m_content_type = "Content-Type: text/html; charset=\"gb2312\"";
mes=m_content_type+End;
mes=mes+"From: "+from+End;
mes=mes+"to: "+to+End;
mes=mes+"subject: "+subject+End+End;
mes=mes+message+End+"."+End;
parms.out.write(mes);
parms.mailout.println(mes); parms.mailout.flush();
String line=parms.mailIn.readLine();
parms.out.println("S: "+line);
}
%>
<%
String host="10.2.0.1";
String from="nsi10219@nsi";
String to="nsi10121@nsi"; String subject="This is subject";
String message="中文信息"; %> <h3>Send Mail log</h3>
<%out.println("<pre>");
Parameters parms=new Parameters();
parms.out=out;
parms.socket=new Socket(host,25);
parms.mailout = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(
parms.socket.getOutputStream())),true); parms.mailIn=new BufferedReader(new InputStreamReader(parms.socket.getInputStream())); String line=parms.mailIn.readLine();
parms.out.println("S :"+line);
sendCommand(parms,"HELO"+host);
sendCommand(parms,"Mail from :"+from);
sendCommand(parms,"Rcpt to :"+to);
sendCommand(parms,"DATA"); sendData(parms,from,to,subject,message);
sendCommand(parms,"QUIT");
parms.socket.close();
out.println("</pre>");
%>
</html>
<?cocoon-process type="xsp"?>
<?cocoon-process type="xslt"?>
<?xml-stylesheet href="sendmail.xsl" type="text/xsl"?><xsp:page language="java" xmlns:xsp="http://www.apache.org/1999/XSP/Core"><xsp:structure>
<xsp:include>java.io.*</xsp:include>
<xsp:include>javax.activation.*</xsp:include>
<xsp:include>java.util.*</xsp:include>
<xsp:include>javax.mail.*</xsp:include>
<xsp:include>javax.mail.internet.*</xsp:include>
</xsp:structure><xsp:logic>
<!--用户认证类-->
public class SmtpAuthenticator extends javax.mail.Authenticator
{
String usr=null;
String pw=null;
public SmtpAuthenticator(String user,String pass)
{
this.usr = user;
this.pw = pass;
}
protected javax.mail.PasswordAuthentication getPasswordAuthentication()
{
return new javax.mail.PasswordAuthentication(usr, pw);
}
}
//中文处理
public String getStr(String str)
{
try
{
String temp_p=str;
byte[] temp_t=temp_p.getBytes("ISO8859-1");
String temp=new String(temp_t);
return temp;
}
catch(Exception e)
{
}
return "null";
}
</xsp:logic><page> <xsp:logic>
Transport transport;
String to_Addr = request.getParameter("TO_ADDR");
String from_Addr = request.getParameter("FROM_ADDR");
String Subject = getStr(request.getParameter("SUBJECT"));
String Body = getStr(request.getParameter("CONTENT"));
String atts = null;
if(request.getParameter("attachFile") != null)
{
atts = request.getParameter("attachFile");
}
String msg1 = "";
String msg2 = ""; String smtp_addr = (String) session.getAttribute("SMTP_ADDR");
String username = (String) session.getAttribute("USERNAME");
String password = (String) session.getAttribute("PASSWORD");
String needed = (String) session.getAttribute("NEEDED"); if(smtp_addr != null
&& username != null
&& password != null)
{
//发送过程
Properties props = System.getProperties();
props.put("mail.smtp.auth", needed);
props.put("mail.smtp.host", smtp_addr);
//用户认证过程
SmtpAuthenticator sa = new SmtpAuthenticator(username,password);
Session sess=Session.getInstance(props,sa);
sess.setDebug(false); if(from_Addr != null
&& to_Addr != null)
{
Message msg=new MimeMessage(sess);
msg.setSentDate(new Date());
msg.setFrom(new InternetAddress(from_Addr));
msg.setRecipient(Message.RecipientType.TO,new InternetAddress(to_Addr));
msg.setSubject(Subject);
if(atts!=null)
{
MimeBodyPart mbp1=new MimeBodyPart();
mbp1.setContent(Body,"text/plain;charset=Gb2312");
MimeBodyPart mbp2=new MimeBodyPart();
FileDataSource fds=new FileDataSource(atts);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
Multipart mp=new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
msg.setContent(mp);
}
else
{
msg.setContent(Body,"text/plain;charset=Gb2312");
}
transport=sess.getTransport("smtp");
if(needed.equals("true"))
{
transport.connect(smtp_addr,username,password);
transport.sendMessage(msg,msg.getAllRecipients());
}
else
{
transport.send(msg);
}
transport.close();
}
}
else
response.sendRedirect("login.xml");
<!---->
</xsp:logic> <message1><xsp:expr>msg1</xsp:expr></message1>
<message2><xsp:expr>to_Addr</xsp:expr></message2>
<message3><xsp:expr>msg2</xsp:expr></message3>
<test><xsp:expr>atts</xsp:expr></test> </page>
</xsp:page>
方法都在里面啦,自己可以抽出来,java可以代码复用
if(request.getParameter("attachFile") != null)
{
atts = request.getParameter("attachFile");
}
这是得到附件的路径,你需要修改,因为这是Cocoon编程,到时候你可以直接赋值就可以啦,其他雷同。或者[email protected]探讨探讨。
/*
* Copyright (c) 2000 David Flanagan. All rights reserved.
* This code is from the book Java Examples in a Nutshell, 2nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book (recommended),
* visit http://www.davidflanagan.com/javaexamples2.
*/
package com.davidflanagan.examples.net;
import java.io.*;
import java.net.*;/**
* This program sends e-mail using a mailto: URL
**/
public class SendMail {
public static void main(String[] args) {
try {
// If the user specified a mailhost, tell the system about it.
if (args.length >= 1)
System.getProperties().put("mail.host", args[0]);
// A Reader stream to read from the console
BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));
// Ask the user for the from, to, and subject lines
System.out.print("From: ");
String from = in.readLine();
System.out.print("To: ");
String to = in.readLine();
System.out.print("Subject: ");
String subject = in.readLine();
// Establish a network connection for sending mail
URL u = new URL("mailto:" + to); // Create a mailto: URL
URLConnection c = u.openConnection(); // Create its URLConnection
c.setDoInput(false); // Specify no input from it
c.setDoOutput(true); // Specify we'll do output
System.out.println("Connecting..."); // Tell the user
System.out.flush(); // Tell them right now
c.connect(); // Connect to mail host
PrintWriter out = // Get output stream to host
new PrintWriter(new OutputStreamWriter(c.getOutputStream())); // Write out mail headers. Don't let users fake the From address
out.print("From: \"" + from + "\" <" +
System.getProperty("user.name") + "@" +
InetAddress.getLocalHost().getHostName() + ">\n");
out.print("To: " + to + "\n");
out.print("Subject: " + subject + "\n");
out.print("\n"); // blank line to end the list of headers // Now ask the user to enter the body of the message
System.out.println("Enter the message. " +
"End with a '.' on a line by itself.");
// Read message line by line and send it out.
String line;
for(;;) {
line = in.readLine();
if ((line == null) || line.equals(".")) break;
out.print(line + "\n");
}
// Close (and flush) the stream to terminate the message
out.close();
// Tell the user it was successfully sent.
System.out.println("Message sent.");
}
catch (Exception e) { // Handle any exceptions, print error message.
System.err.println(e);
System.err.println("Usage: java SendMail [<mailhost>]");
}
}
}