发送邮件(三)


import java.io.File;
import java.util.Date;
import java.util.Properties;
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;

public class TestMail {

        public static void main(String[] args) {

            String from = "xxxxx@qq.com"; //发件人的邮箱地址
            String to = "xxxxx@qq.com";    //收件人的邮箱地址
            String subject = "邮件+附件";    //邮件主题
            String body = "正文部分";    //邮件内容

            //设置发送邮件的一些属性
            Properties prop = new Properties();
            prop.setProperty("mail.transport.protocol", "smtp");
            prop.setProperty("mail.smtp.host", "smtp.qq.com");
            prop.setProperty("mail.smtp.port", "465");
            prop.setProperty("mail.smtp.auth", "true");
            prop.setProperty("mail.debug", "true");
            prop.setProperty("mail.smtp.ssl.enable", "true"); //qq邮箱必须设置这一项,ssl加密选项


            Session session = Session.getDefaultInstance(prop, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    //这里需要验证邮箱的授权码,QQ邮箱需要授权码
                    return new PasswordAuthentication(from, "授权码");
                }
            });

            MimeMessage message = new MimeMessage(session);
            try {
                Transport transport = session.getTransport();
                message.setFrom(new InternetAddress(from));
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
                message.setSentDate(new Date());
                message.setSubject(subject);

                // 创建消息体部分
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setText("这是邮件正文");

                // 创建多重消息
                Multipart multipart = new MimeMultipart();
                multipart.addBodyPart(messageBodyPart); // 将消息体部分加入到多重消息中

                // 创建一个附件
                messageBodyPart = new MimeBodyPart();
                File file = new File("D:\\Study\\JAVA\\mail-java\\src\\bz.jpg");
                DataSource source = new FileDataSource(file);
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName("file");
                multipart.addBodyPart(messageBodyPart);

                message.setContent(multipart);
                message.saveChanges();
                session.setDebug(true);
                transport.connect(from, "授权码");
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
posted @ 2020-06-17 15:04  忘山川  阅读(123)  评论(0编辑  收藏  举报