java发生邮件(转)

Posted guoDaXia的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java发生邮件(转)相关的知识,希望对你有一定的参考价值。

参考链接:http://www.runoob.com/java/java-sending-email.html

 

package test.mail;
import com.sun.mail.util.MailSSLSocketFactory;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.Properties;

/**
 * @author
 * Created by zhen on 2017-11-01.
 */
public class EmailUtil {

    public static void SendMail(MailConfig mailConfig, MailBody mailBody) throws Exception{

        //获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", mailConfig.getHost());

        Authenticator authenticator = null;
        if(mailConfig.isAuth()){
            //设置进行认证
            properties.put("mail.smtp.auth", "true");

            //设置认证参数
            authenticator = new Authenticator(){
                @Override
                public PasswordAuthentication getPasswordAuthentication()
                {
                    return new PasswordAuthentication(mailConfig.getUserName(), mailConfig.getPassword()); //发件人邮件用户名、密码
                }
            };

            if(mailConfig.isQQ()){ //假如是QQ邮箱
                MailSSLSocketFactory sf = new MailSSLSocketFactory();
                sf.setTrustAllHosts(true);
                properties.put("mail.smtp.ssl.enable", "true");
                properties.put("mail.smtp.ssl.socketFactory", sf);
            }
        }

        //获取默认的Session对象
        Session session = Session.getDefaultInstance(properties, authenticator);

        //创建默认的MimeMessage对象
        MimeMessage message = new MimeMessage(session);

        // set from: 头部字段
        message.setFrom(new InternetAddress(mailConfig.getFrom()));

        //set To: 头部字段
        String[] tos = mailConfig.getTOs();
        String[] bccs = mailConfig.getBCCs();
        String[] ccs = mailConfig.getCCs();
        InternetAddress[] toAddress = new InternetAddress[tos.length];
        InternetAddress[] bccAddress = new InternetAddress[bccs.length];
        InternetAddress[] ccAddress = new InternetAddress[ccs.length];
        for(int i = 0; i < tos.length; i++){
            toAddress[i] = new InternetAddress(tos[i]);
        }
        for(int i = 0; i < bccs.length; i++){
            bccAddress[i] = new InternetAddress(bccs[i]);
        }
        for(int i = 0; i < ccs.length; i++){
            ccAddress[i] = new InternetAddress(ccs[i]);
        }
        message.addRecipients(Message.RecipientType.TO, toAddress);
        message.addRecipients(Message.RecipientType.BCC, bccAddress);
        message.addRecipients(Message.RecipientType.CC, ccAddress);

        // set Subject: 头字段
        message.setSubject(mailBody.getSubject());

        //创建消息部分
        BodyPart messageBodyPart = new MimeBodyPart();

        //消息
        messageBodyPart.setContent(mailBody.getContent(), mailBody.getContentType());

        //创建多重消息
        Multipart multipart = new MimeMultipart();

        //设置消息部分
        multipart.addBodyPart(messageBodyPart);

        //附件部分
        for(File attachment : mailBody.getAttachments()){
            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(attachment.getName());
            multipart.addBodyPart(messageBodyPart);
        }

        //设置完整消息
        message.setContent(multipart);

        //发送消息
        Transport.send(message);

    }

}
class MailConfig{
    private String from;
    private String[] TOs;
    private String[] BCCs;
    private String[] CCs;
    private String host;
    private boolean isAuth;
    private String userName;
    private String password;
    private boolean isQQ;

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String[] getTOs() {
        return TOs;
    }

    public void setTOs(String[] TOs) {
        this.TOs = TOs;
    }

    public String[] getBCCs() {
        return BCCs;
    }

    public void setBCCs(String[] BCCs) {
        this.BCCs = BCCs;
    }

    public String[] getCCs() {
        return CCs;
    }

    public void setCCs(String[] CCs) {
        this.CCs = CCs;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public boolean isAuth() {
        return isAuth;
    }

    public void setAuth(boolean auth) {
        isAuth = auth;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isQQ() {
        return isQQ;
    }

    public void setQQ(boolean QQ) {
        isQQ = QQ;
    }
}
class MailBody{
    private String subject;
    private Object content;
    private String contentType;
    private File[] attachments;

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public Object getContent() {
        return content;
    }

    public void setContent(Object content) {
        this.content = content;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public File[] getAttachments() {
        return attachments;
    }

    public void setAttachments(File[] attachments) {
        this.attachments = attachments;
    }
}


package test.mail;

        import com.sun.mail.util.logging.MailHandler;

        import java.io.File;

        import javax.activation.DataHandler;
        import javax.activation.DataSource;
        import javax.activation.FileDataSource;
        import javax.mail.*;
        import javax.mail.internet.*;
        import java.util.Properties;

/**
 * @author
 * Created by zhen on 2017-11-01.
 */
public class SendEmail {

    public void sendSimpleEmail(String[] args) {


        //收件人电子邮箱
        String to = "[email protected]";

        //发件人电子邮箱
        String from = "[email protected]";

        //指定发送主机
        String host = "smtp.126.com";

        //获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);

        //设置进行认证
        properties.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(properties, new Authenticator(){
            @Override
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication("[email protected]", "899496gz"); //发件人邮件用户名、密码
            }
        });

        try{
            //创建默认的MimeMessage对象
            MimeMessage message = new MimeMessage(session);

            //set From;头部字段
            message.setFrom(new InternetAddress(from));

            //set To:头部字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            //set Subject: 头部字段
            message.setSubject("This is the Subject Line");

            //设置消息体
            message.setText("This is actual message");

            //发送消息
            Transport.send(message);

        }catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void sendHTMLEmail() {

        //收件人电子邮箱
        String to = "[email protected]";

        //发件人电子邮箱
        String from = "[email protected]";

        //指定发送主机
        String host = "smtp.126.com";

        //获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);

        //设置进行认证
        properties.put("mail.smtp.auth", "true");

        //获取默认的Session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator(){
            @Override
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication("[email protected]", "899496gz"); //发件人邮件用户名、密码
            }
        });

        try{
            //创建默认的MimeMessage对象
            MimeMessage message = new MimeMessage(session);

            // set from: 头部字段
            message.setFrom(new InternetAddress(from));

            //set To: 头部字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            // set Subject: 头字段
            message.setSubject("This is the Subject Line!");

            //发送HTML消息,可以插入HTML标签
            message.setContent("<h1><font color=\"red\">This is actual message</font><h1>", "text/html");

            //发送消息
            Transport.send(message);

        }catch(Exception ex) {
            ex.printStackTrace();
        }

    }

    public void sendWithAttachment(String[] args){
        //收件人电子邮箱
        String to = "[email protected]";

        //发件人电子邮箱
        String from = "[email protected]";

        //指定发送主机
        String host = "smtp.126.com";

        //获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);

        //设置进行认证
        properties.put("mail.smtp.auth", "true");

        //获取默认的Session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator(){
            @Override
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication("[email protected]", "899496gz"); //发件人邮件用户名、密码
            }
        });

        try{
            //创建默认的MimeMessage对象
            MimeMessage message = new MimeMessage(session);

            // set from: 头部字段
            message.setFrom(new InternetAddress(from));

            //set To: 头部字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            // set Subject: 头字段
            message.setSubject("This is the Subject Line!");

            //创建消息部分
            BodyPart messageBodyPart = new MimeBodyPart();

            //消息
            messageBodyPart.setContent("<h1><font color=\"red\">This is actual message</font><h1>", "text/html");

            //创建多重消息
            Multipart multipart = new MimeMultipart();

            //设置文本消息部分
            multipart.addBodyPart(messageBodyPart);

            //附件部分
            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource("file.txt"); //目录位置为项目的根路径 F:/test/file.txt
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName("file.txt");
            multipart.addBodyPart(messageBodyPart);

            //设置完整消息
            message.setContent(multipart);

            //发送消息
            Transport.send(message);

        }catch(Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MailConfig mailConfig = new MailConfig();
        mailConfig.setAuth(true);
        mailConfig.setHost("smtp.qq.com");
        mailConfig.setTOs(new String[]{"[email protected]"});
        mailConfig.setBCCs(new String[]{"[email protected]"});
        mailConfig.setCCs(new String[]{});
        mailConfig.setUserName("[email protected]");
        mailConfig.setFrom("[email protected]");
        mailConfig.setPassword("ezmfkuhobxtqdbfi");
        mailConfig.setQQ(true);

        MailBody mailBody = new MailBody();
        mailBody.setSubject("一封测试邮件");
        mailBody.setContent("你好吗?guoDaXia!");
        mailBody.setContentType("text/plain;charset=UTF-8");
        mailBody.setAttachments(new File[]{new File("file.txt")});

        try {
            EmailUtil.SendMail(mailConfig, mailBody);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

 

以上是关于java发生邮件(转)的主要内容,如果未能解决你的问题,请参考以下文章

关于java mail 发邮件的问题总结(转)

javamail发送邮件(转)

java 当数据库数据发生变化时自动发送邮件

这些角度电子邮件指令代码片段如何连接

超实用的php代码片段

我应该如何使用 Outlook 发送代码片段?