java程序发送邮件


一、

import java.io.File;
import java.security.GeneralSecurityException;
import java.util.Calendar;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
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.AddressException;
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;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sun.mail.util.MailSSLSocketFactory;

public class MailInfo
{
    // ================================属性==================================

    private final Log log = LogFactory.getLog(MailInfo.class);

    // 发送邮件的服务器的IP和端口、用户名、密码(系统共用一个账号,声明为static final)
    private static final String MAILHOST = "smtp.qq.com";
    private static final String MAILPORT = "465";
    private static final String USERNAME = "88888888@qq.com";
    private static final String PASSWORD = "****************";// 第三方授权码

    // 验证信息(系统账号不变,该属性固定不变)
    // TODO 待验证,若有时效性,不能设置为静态
    private static Session session;
    private Message message;

    // 发送邮件的主题、内容、附件
    private String subject;
    private String content;
    private File[] attachments;

    // 发送人(发送人区别于发送邮件账号,系统中共用一个邮件账号,而发送人是获取的系统的登录人)
    private String sender;
    // 接收人
    private Address[] recipients;
    // 抄送人
    private Address[] cc;

    private static final String CHARSET = "utf-8";

    // ================================构造器==================================

    public MailInfo(String subject, String content, File[] attachments, String sender, InternetAddress[] recipients,
            InternetAddress[] cc)
    {
        this.subject = subject;
        this.content = content;
        this.attachments = attachments;

        this.sender = sender;
        this.recipients = recipients;
        this.cc = cc;
        initSession();
        message = new MimeMessage(session);
    }

    private void initSession()
    {
        if (session != null)
            return;

        Properties props = new Properties();
        props.put("mail.smtp.host", MAILHOST);
        props.put("mail.smtp.port", MAILPORT);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");

        MailSSLSocketFactory sslSF = null;
        try
        {
            sslSF = new MailSSLSocketFactory();
        } catch (GeneralSecurityException e)
        {
            log.error("initProps()", e);
        }
        sslSF.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sslSF);
        // 常用的电子邮件协议包括 SMTP,POP3,IMAP,但是邮件的创建和发送只需要用到 SMTP协议(简单邮件传输协议Simple Mail
        // Transfer Protocol)
        props.put("mail.transport.protocol", "smtp");

        props.put("mail.user", USERNAME);
        props.put("mail.password", PASSWORD);
        session = Session.getInstance(props, new MyAuthenticator(USERNAME, PASSWORD));
        session.setDebug(true);
    }

    // ================================方法==================================

    public void doSend() throws Exception
    {
        try
        {
            // 设置邮件发送人
            Address from = new InternetAddress(USERNAME, sender, CHARSET);
            message.setFrom(from);
            // 设置收件人和抄送人
            if (recipients == null || recipients.length == 0)
                throw new Exception("没有收件人!");
            message.setRecipients(Message.RecipientType.TO, recipients);
            if (cc != null && cc.length != 0)
                message.setRecipients(Message.RecipientType.CC, cc);

            // 设置主题、时间
            message.setSubject(subject);
            message.setSentDate(Calendar.getInstance().getTime());

            // Multipart是一个容器类,放置内容和附件
            Multipart multiPart = new MimeMultipart();
            message.setContent(multiPart);

            /*
             * 装填multiPart
             */
            BodyPart bodyPartContent = new MimeBodyPart();
            multiPart.addBodyPart(bodyPartContent);
            // 添加内容
            bodyPartContent.setContent(content, "text/html; charset=utf-8");
            // 添加附件
            if (attachments == null || attachments.length == 0)
                throw new Exception("没有附件!");
            for (File attachment : attachments)
            {
                BodyPart bodyPart = new MimeBodyPart();
                FileDataSource fds = new FileDataSource(attachment);
                bodyPart.setDataHandler(new DataHandler(fds));
                bodyPart.setFileName(MimeUtility.encodeText(fds.getName()));
                multiPart.addBodyPart(bodyPart);
            }

            // 发送信息
            Transport.send(message);
        } catch (AddressException e)
        {
            log.error("doSend()", e);
        } catch (MessagingException e)
        {
            log.error("doSend()", e);
        }
    }

    // ================================内部类==================================
    /**
     * 验证类
     * 
     * @author hasee
     * 
     */
    class MyAuthenticator extends Authenticator
    {
        private String userName = null;
        private String password = null;

        public MyAuthenticator(String userName, String password)
        {
            this.userName = userName;
            this.password = password;
        }

        @Override
        protected PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(userName, password);
        }
    }

    public static void main(String[] args) throws Exception
    {
        String subject = "主题";
        String content = "内容";
        File[] files = { new File("Z:\\linux资料\\test.rar") };
        String sender = "发送人是我";
        InternetAddress[] address = { new InternetAddress("666666@qq.com") };
        InternetAddress[] address2 = {};
        MailInfo mail = new MailInfo(subject, content, files, sender, address, address2);
        mail.doSend();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值