Java 发送邮件

经过实践,发送成功,实例一:

package com.abin.oracle.procedure;

import java.util.Date;  
import java.util.Enumeration;  
import java.util.Properties;  
import java.util.Vector;  
  
import javax.activation.DataHandler;  
import javax.activation.FileDataSource;  
import javax.mail.Authenticator;  
import javax.mail.Message;  
import javax.mail.MessagingException;  
import javax.mail.Multipart;  
import javax.mail.PasswordAuthentication;  
import javax.mail.Session;  
import javax.mail.Transport;  
import javax.mail.internet.InternetAddress;  
import javax.mail.internet.MimeBodyPart;  
import javax.mail.internet.MimeMessage;  
import javax.mail.internet.MimeMultipart;  
import javax.mail.internet.MimeUtility;  

public class SendMail {  
	  
    String to = "";// 收件人   
    String from = "";// 发件人   
    String host = "";// smtp主机   
    String username = "";  
    String password = "";  
    String filename = "";// 附件文件名   
    String subject = "";// 邮件主题   
    String content = "";// 邮件正文   
    Vector file = new Vector();// 附件文件集合   
  
    /** 
     * <br> 
     * 方法说明:默认构造器 <br> 
     * 输入参数: <br> 
     * 返回类型: 
     */  
    public SendMail() {  
    }  
  
    /** 
     * <br> 
     * 方法说明:构造器,提供直接的参数传入 <br> 
     * 输入参数: <br> 
     * 返回类型: 
     */  
    public SendMail(String to, String from, String smtpServer, String username,  
            String password, String subject, String content) {  
        this.to = to;  
        this.from = from;  
        this.host = smtpServer;  
        this.username = username;  
        this.password = password;  
        this.subject = subject;  
        this.content = content;  
    }  
  
    /** 
     * <br> 
     * 方法说明:设置邮件服务器地址 <br> 
     * 输入参数:String host 邮件服务器地址名称 <br> 
     * 返回类型: 
     */  
    public void setHost(String host) {  
        this.host = host;  
    }  
  
    /** 
     * <br> 
     * 方法说明:设置登录服务器校验密码 <br> 
     * 输入参数: <br> 
     * 返回类型: 
     */  
    public void setPassWord(String pwd) {  
        this.password = pwd;  
    }  
  
    /** 
     * <br> 
     * 方法说明:设置登录服务器校验用户 <br> 
     * 输入参数: <br> 
     * 返回类型: 
     */  
    public void setUserName(String usn) {  
        this.username = usn;  
    }  
  
    /** 
     * <br> 
     * 方法说明:设置邮件发送目的邮箱 <br> 
     * 输入参数: <br> 
     * 返回类型: 
     */  
    public void setTo(String to) {  
        this.to = to;  
    }  
  
    /** 
     * <br> 
     * 方法说明:设置邮件发送源邮箱 <br> 
     * 输入参数: <br> 
     * 返回类型: 
     */  
    public void setFrom(String from) {  
        this.from = from;  
    }  
  
    /** 
     * <br> 
     * 方法说明:设置邮件主题 <br> 
     * 输入参数: <br> 
     * 返回类型: 
     */  
    public void setSubject(String subject) {  
        this.subject = subject;  
    }  
  
    /** 
     * <br> 
     * 方法说明:设置邮件内容 <br> 
     * 输入参数: <br> 
     * 返回类型: 
     */  
    public void setContent(String content) {  
        this.content = content;  
    }  
  
    /** 
     * <br> 
     * 方法说明:把主题转换为中文 <br> 
     * 输入参数:String strText <br> 
     * 返回类型: 
     */  
    public String transferChinese(String strText) {  
        try {  
            strText = MimeUtility.encodeText(new String(strText.getBytes(),  
                    "GB2312"), "GB2312", "B");  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return strText;  
    }  
  
    /** 
     * <br> 
     * 方法说明:往附件组合中添加附件 <br> 
     * 输入参数: <br> 
     * 返回类型: 
     */  
    public void attachfile(String fname) {  
        file.addElement(fname);  
    }  
  
    /** 
     * <br> 
     * 方法说明:发送邮件 <br> 
     * 输入参数: <br> 
     * 返回类型:boolean 成功为true,反之为false 
     */  
    public boolean sendMail() {  
  
        // 构造mail session   
        Properties props = System.getProperties();  
        props.put("mail.smtp.host", host);  
        props.put("mail.smtp.auth", "true");  
        Session session = Session.getDefaultInstance(props,  
                new Authenticator() {  
                    public PasswordAuthentication getPasswordAuthentication() {  
                        return new PasswordAuthentication(username, password);  
                    }  
                });  
  
        try {  
            // 构造MimeMessage 并设定基本的值   
            MimeMessage msg = new MimeMessage(session);  
            msg.setFrom(new InternetAddress(from));  
            InternetAddress[] address = { new InternetAddress(to) };  
            msg.setRecipients(Message.RecipientType.TO, address);  
            subject = transferChinese(subject);  
            msg.setSubject(subject);  
  
            // 构造Multipart   
            Multipart mp = new MimeMultipart();  
  
            // 向Multipart添加正文   
            MimeBodyPart mbpContent = new MimeBodyPart();  
            mbpContent.setText(content);  
            // 向MimeMessage添加(Multipart代表正文)   
            mp.addBodyPart(mbpContent);  
  
            // 向Multipart添加附件   
            Enumeration efile = file.elements();  
            while (efile.hasMoreElements()) {  
  
                MimeBodyPart mbpFile = new MimeBodyPart();  
                filename = efile.nextElement().toString();  
                FileDataSource fds = new FileDataSource(filename);  
                mbpFile.setDataHandler(new DataHandler(fds));  
                mbpFile.setFileName(fds.getName());  
                // 向MimeMessage添加(Multipart代表附件)   
                mp.addBodyPart(mbpFile);  
  
            }  
  
            file.removeAllElements();  
            // 向Multipart添加MimeMessage   
            msg.setContent(mp);  
            msg.setSentDate(new Date());  
            // 发送邮件   
            Transport.send(msg);  
  
        } catch (MessagingException mex) {  
            mex.printStackTrace();  
            Exception ex = null;  
            if ((ex = mex.getNextException()) != null) {  
                ex.printStackTrace();  
            }  
            return false;  
        }  
        return true;  
    }  
  
    /** 
     * <br> 
     * 方法说明:主方法,用于测试 <br> 
     * 输入参数: <br> 
     * 返回类型: 
     */  
    public static void main(String[] args) {  
        SendMail sendmail = new SendMail();  
        sendmail.setHost("smtp.163.com");//smtp.mail.yahoo.com.cn    
        sendmail.setUserName("lee");//您的邮箱用户名   
        sendmail.setPassWord("*****");//您的邮箱密码   
        sendmail.setTo("[email protected]");//接收者   
        sendmail.setFrom("[email protected]");//发送者   
        sendmail.setSubject("你好,这是测试2!");  
        sendmail.setContent("你好这是一个带多附件的测试2!");  
        sendmail.attachfile("c:/attachment1.txt");  
        sendmail.attachfile("c:/attachment2.txt");  
        sendmail.sendMail();  
  
    }  
}// end  





经过实践,发送成功,实例二:

package com.abin.oracle.procedure;

import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Test
{
    // 邮箱服务器
    private String host = "smtp.163.com";
    // 这个是你的邮箱用户名
    private String username = "lee";
    // 你的邮箱密码
    private String password = "*******";
    
    private String mail_head_name = "this is head of this mail";

    private String mail_head_value = "this is head of this mail";

    private String mail_to = "[email protected]";

    private String mail_from = "[email protected]";

    private String mail_subject = "this is the subject of this test mail";

    private String mail_body = "this is the mail_body of this test mail";

    private String personalName = "我的邮件";

    public Test()
    {
    }

    /** *//**
     * 此段代码用来发送普通电子邮件
     */
    public void send() throws Exception
    {
        try
        {
            Properties props = new Properties(); // 获取系统环境
            Authenticator auth = new Email_Autherticator(); // 进行邮件服务器用户认证
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.auth", "true");
            Session session = Session.getDefaultInstance(props, auth);
            // 设置session,和邮件服务器进行通讯。
            MimeMessage message = new MimeMessage(session);
            // message.setContent("foobar, "application/x-foobar"); // 设置邮件格式
            message.setSubject(mail_subject); // 设置邮件主题
            message.setText(mail_body); // 设置邮件正文
            message.setHeader(mail_head_name, mail_head_value); // 设置邮件标题
            message.setSentDate(new Date()); // 设置邮件发送日期
            Address address = new InternetAddress(mail_from, personalName);
            message.setFrom(address); // 设置邮件发送者的地址
            Address toAddress = new InternetAddress(mail_to); // 设置邮件接收方的地址
            message.addRecipient(Message.RecipientType.TO, toAddress);
            Transport.send(message); // 发送邮件
            System.out.println("send ok!");
        } catch (Exception ex)
        {
            ex.printStackTrace();
            throw new Exception(ex.getMessage());
        }
    }

    /** *//**
     * 用来进行服务器对用户的认证
     */
    public class Email_Autherticator extends Authenticator
    {
        public Email_Autherticator()
        {
            super();
        }

        public Email_Autherticator(String user, String pwd)
        {
            super();
            username = user;
            password = pwd;
        }

        public PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(username, password);
        }
    }

    public static void main(String[] args)
    {
        Test sendmail = new Test();
        try
        {
            sendmail.send();
        } catch (Exception ex)
        {
        }
    }

}




遇到的问题是:
我用的是Myeclipse6.5
报的错误:
Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
解决办法:
Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
这个问题是由于Javaee5中的mail还存在一些问题,和原来的mail.jar和activition.jar存在冲突。
如果你用myEclipse进行开发的话,运行时可能会出现以下的错误:
Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
原因是jar包版本不统一,解决方法如下:

删除Java EE 5 Libraries/javaee.jar/mail里的包有东西,如果还是不行把activition也删了。

具体方法如下:
用 rar打开X:/Program Files/MyEclipse 6.0/myeclipse/eclipse/plugins/com.genuitec.eclipse.j2eedt.core_6.0.1.zmyeclipse601200710/data/libraryset/EE_5/javaee.jar
,然后删除mail,一接着把以前的mail.jar和activition.jar导入即可。


用到的JAR包,下面有:


你可能感兴趣的:(java)