当前位置: 技术问答>java相关
那位老兄有java(jsp、servlet)发邮件的源代码?
来源: 互联网 发布时间:2015-07-15
本文导语: 我想做个发邮件的程序,只需实现发邮件基本功能,不用发附件。一定要好用。如果有的话请发过来,网上有一些不过大都不好用。最好是验证过的,如好用本人将另开贴酬谢!无聊者请勿打扰,谢谢! Email:bingziice...
我想做个发邮件的程序,只需实现发邮件基本功能,不用发附件。一定要好用。如果有的话请发过来,网上有一些不过大都不好用。最好是验证过的,如好用本人将另开贴酬谢!无聊者请勿打扰,谢谢!
Email:bingziice@sina.com
Email:bingziice@sina.com
|
发送电子邮件
Send Mail log
|
java.io.*
javax.activation.*
java.util.*
javax.mail.*
javax.mail.internet.*
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";
}
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");
msg1
to_Addr
msg2
atts
方法都在里面啦,自己可以抽出来,java可以代码复用
|
***** 教材示例 *********
/*
* 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 + "" 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 []");
}
}
}
/*
* 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 + "" 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 []");
}
}
}