起步软件技术论坛
搜索
 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 2200|回复: 0

[分享] JAVA发送带附件的邮件(附件来自attachmentSimple)

[复制链接]

53

主题

928

帖子

1730

积分

金牌会员

Rank: 6Rank: 6

积分
1730
发表于 2017-6-5 15:21:05 | 显示全部楼层 |阅读模式
package zwzx;
import java.io.IOException;
import java.io.File;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
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.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.action.ActionContext;
import javax.mail.Multipart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeBodyPart;


public class Sendmail{
        public static JSONObject sendEmail(JSONObject params, ActionContext context) throws ServletException, IOException, AddressException, MessagingException {
                //获取邮箱
                String receiveUser = params.getString("receiveUser");
                String sendHtml = params.getString("sendHtml");
                String subject = params.getString("subject");
                String[] ownerID = params.getString("ownerID").replace("[", "").replace("]", "").replace("\"", "").split(",");
                String[]storeFileName = params.getString("storeFileName").replace("[", "").replace("]", "").replace("\"", "").split(",");
                String[] name = params.getString("name").replace("[", "").replace("]", "").replace("\"", "").split(",");
               
               
                //设置发送者的用户名
                String SEND_UNAME = "QQ";
                //设置发送者的授权码
                String SEND_PWD = "QQ授权码";
                String VALUE_SMTP = "smtp.qq.com";
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                Properties props = System.getProperties();
                props.setProperty("mail.smtp.host", "smtp.qq.com");
                props.setProperty("mail.smtp.port", "25");
                props.put("mail.smtp.auth", "true");
                props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                props.setProperty("mail.smtp.port", "465");
                props.setProperty("mail.smtp.socketFactory.port", "465");
               
                final String username = "QQ";
                final String password = "QQ授权码";
                Session session = Session.getDefaultInstance(props,
                        new Authenticator() {
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(username, password);
                            }
                        });
               
                session.setDebug(true);
                Message msg = new MimeMessage(session);
               
                msg.setFrom(new InternetAddress(username + "@qq.com"));
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
                                receiveUser, false));
                msg.setSentDate(new Date());
                msg.setSubject(subject);
                String VerifCode = sendHtml;
                // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
                Multipart multipart = new MimeMultipart();
        //   设置邮件的文本内容
                BodyPart contentPart = new MimeBodyPart();
                contentPart.setText(VerifCode);
                multipart.addBodyPart(contentPart);
                //添加附件
                for(int i=0;i< storeFileName.length;i++){
                BodyPart messageBodyPart= new MimeBodyPart();
                File sendfile = new File(docStorePath + File.separator +ownerID[i] + File.separator + storeFileName[i]);
        DataSource source = new FileDataSource(sendfile);
      //添加附件的内容
        messageBodyPart.setDataHandler(new DataHandler(source));
      //添加附件的标题
        String fileName=sendfile.getName();
        String prefix=fileName.substring(fileName.lastIndexOf("."));
        messageBodyPart.setFileName(MimeUtility.encodeWord(name[i]+prefix));
        multipart.addBodyPart(messageBodyPart);       
                }
       
      //将multipart对象放到message中
        msg.setContent(multipart);
      //保存邮件
        msg.saveChanges();
      
        msg.setSentDate(new Date());
        Transport transport = session.getTransport("smtp");
                // smtp验证,就是你用来发邮件的邮箱用户名和授权码
                transport.connect(VALUE_SMTP, SEND_UNAME, SEND_PWD);
                // 发送
                transport.sendMessage(msg, msg.getAllRecipients());
                transport.close();
                return null;
        }
        static String docStorePath;
        static File docStoreDir;
       
        static{
                String baasPath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + ".."+ File.separator + ".." ;
                docStorePath = baasPath + File.separator + "data" + File.separator + "attachmentSimple"+ File.separator +"zwzx";
                File file = new File(docStorePath);
                //兼容以前存储目录
                if(file.exists() && file.isDirectory()){
                        docStoreDir = file;
                }
        }
       
       
        public static File getDocStoreDir(HttpServletRequest request) {
                if(docStoreDir == null){
                        ServletContext context = request.getSession().getServletContext();
                        String path = context.getRealPath("/");
                        docStorePath =  path + "../../data/attachmentSimple/zwzx";
                        File file = new File(docStorePath);
                        if(!file.exists()){
                                file.mkdirs();
                        }
                        docStoreDir = file;
                }
                return docStoreDir;
        }
}

评分

参与人数 1威望 +15 收起 理由
ysk007 + 15 很给力!

查看全部评分

您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|X3技术论坛|Justep Inc.    

GMT+8, 2025-7-11 16:54 , Processed in 0.068670 second(s), 23 queries .

Powered by Discuz! X3.4

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表