当前位置:   article > 正文

java实现邮件发送接收功能_java接收邮件

java接收邮件

一:依赖包

	<!--发送邮件依赖jar包-->
		<!-- https://mvnrepository.com/artifact/javax.mail/javax.mail-api -->
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>javax.mail-api</artifactId>
			<version>1.6.1</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
		<dependency>
			<groupId>com.sun.mail</groupId>
			<artifactId>javax.mail</artifactId>
			<version>1.6.1</version>
		</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

二:发送邮件(发送邮件逻辑是互通的,支持各大平台的发送)


package com.ml.common.utils.email;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**

 */
public class EmailUtil {

    protected final Logger logger = LoggerFactory.getLogger(getClass());


    /**
     * 邮箱格式校验
     * create by: jkun
     * @return
     */
    public static boolean emailFormat(String email) {
        boolean tag = true;
        if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
            tag = false;
        }
        return tag;
    }
    /**
     * 发送简单文本邮件 标题+内容
     * @param title  标题
     * @param context  内容
     * @param emailAddress 邮箱地址
     * @Param attachmentUrl 附件地址
     *
     */
    public static boolean sendSimpleMail(String title, String context,String emailAddress, String attachmentUrl) throws Exception {
        Transport transport = null;
        // 参数配置,勿随意更改
        System.setProperty("mail.mime.splitlongparameters","false");
        Properties props = new Properties();
        props.put("mail.smtp.host","smtp.aliyun.com"); // 设置发送邮件的邮件服务器的属性(这里使用阿里云的smtp服务器)
        props.put("mail.smtp.auth", "true"); // 需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条)
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");

        Session session = Session.getDefaultInstance(props);
        session.setDebug(true);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("734514801@aliyun.com"/*删除此段-发件邮箱*/,"陈光照"/*发件人姓名*/,"UTF-8"));// 加载发件人地址
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress)); // 加载收件人地址
        message.setSubject(title); // 加载标题
        message.setSentDate(new Date()); //	设置发送时间

        // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
        Multipart multipart = new MimeMultipart();
        BodyPart contentPart = new MimeBodyPart(); // 设置邮件的文本内容
        contentPart.setText(context);
//        contentPart.setContent(context,"text/html;charset=utf-8");
        multipart.addBodyPart(contentPart);
        // 添加附件
        if (StringUtils.isNotBlank(attachmentUrl)){
            String fileFormat = attachmentUrl.substring(attachmentUrl.lastIndexOf(".") + 1, attachmentUrl.length());
            String fileName = null;
            if (attachmentUrl.lastIndexOf("=") != -1){
                fileName = attachmentUrl.substring(attachmentUrl.lastIndexOf("=") +1, attachmentUrl.length());
            }
            else if (attachmentUrl.lastIndexOf("/") != -1){
                fileName = attachmentUrl.substring(attachmentUrl.lastIndexOf("/") +1, attachmentUrl.length());
            }
            BodyPart messageBodyPart = new MimeBodyPart();

            URLDataSource source = new URLDataSource(new URL(attachmentUrl));
            // 添加附件的内容
            messageBodyPart.setDataHandler(new DataHandler(source));
            // 添加附件的标题
            // 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱
            messageBodyPart.setFileName(MimeUtility.encodeText(fileName));
            multipart.addBodyPart(messageBodyPart);


        }
        message.setContent(multipart);
        message.saveChanges(); // 保存邮件
        transport = session.getTransport("smtp"); // 发送邮件
        transport.connect("734514801@aliyun.com", /*阿里邮箱授权码*/"填写阿里云邮箱密码或者授权码"/*删除此段-发件人邮箱授权密码*/);//
        try {
            transport.sendMessage(message, message.getAllRecipients()); // 把邮件发送出去
        } catch (Exception e){
            return false;
        }finally {
            try {
                if (transport != null) {
                    transport.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return true;
    }
    public static void main(String[] args) throws Exception 
		 sendSimpleMail("测试","测试1","734514801@qq.com",null);
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125

三:接收邮箱

//这是html内容转字符串内容(看业务用)
public class Html2TextUtil extends HTMLEditorKit.ParserCallback {

    private StringBuffer stringBuffer;
    private List<String> stringBufferList;
    private List<Integer> stringBufferPos;
    private static Html2TextUtil html2Text = new Html2TextUtil();

    public Html2TextUtil() {
    }

    public void parse(String str) {

        InputStream iin = new ByteArrayInputStream(str.getBytes());
        Reader in = new InputStreamReader(iin);
        stringBuffer = new StringBuffer();
        stringBufferList=new ArrayList<String>();
        stringBufferPos=new ArrayList<Integer>();
        ParserDelegator delegator = new ParserDelegator();
        try {
            delegator.parse(in, this, Boolean.TRUE);
        }catch (Exception e){
        }finally {
            if(in !=null){
                try {
                    in.close();
                }catch (Exception ee){

                }
            }
            if(iin !=null){
                try {
                    iin.close();
                }catch (Exception ee){

                }
            }
        }
    }

    public void handleText(char[] text, int pos) {
        String textStr=String.valueOf(text);
        if(textStr!=null&&!"".equals(textStr)){
            stringBufferList.add(textStr);
            stringBufferPos.add(pos);
        }
        stringBuffer.append(text);
    }

    public String getText() {
        return stringBuffer.toString();
    }
    public Map<String,Object> getSplitText() {
        Map<String,Object> map=new Hashtable<String,Object>();
        map.put("text",stringBuffer.toString());
        map.put("textList",stringBufferList);
        map.put("textPos",stringBufferPos);
        return map;
    }
    public void flush() throws BadLocationException {
    }

    public void handleComment(char[] var1, int var2) {
    }

    public void handleStartTag(HTML.Tag var1, MutableAttributeSet var2, int var3) {
    }

    public void handleEndTag(HTML.Tag var1, int var2) {
    }

    public void handleSimpleTag(HTML.Tag var1, MutableAttributeSet var2, int var3) {
    }

    public void handleError(String var1, int var2) {
    }

    public void handleEndOfLineString(String var1) {
    }
    public static String getContent(String str) {
        html2Text.parse(str);
       return html2Text.getText();
    }
    public static  Map<String,Object> getContentMap(String str) {
        html2Text.parse(str);
        return html2Text.getSplitText();
    }
    public static void  main(String[] args){
        String s1 = "<p></p><p>考生注意:</p><p style=\"text-indent: 2em;\">1.本试卷分选择题和非选择题两部分。满分100分,考试时间90分钟。</p><p style=\"text-indent: 2em;\">2.答题前,考生务必用直径0. 5毫米黑色墨水签字笔将密封线内项目填写清楚。</p>";

        String result=new Html2TextUtil().getContent(s1);
        System.out.println("【原始html为】:"+s1);
        System.out.println("【纯文本字符串为】:"+result);
        System.out.println();
        Map<String,Object> htmlMap=new Html2TextUtil().getContentMap(s1);
        System.out.println("【原始html】:"+s1);
        List<String> list= (List<String>)htmlMap.get("textList");
        for(String str:list){
            System.out.println(str);
        }
    }

}

package com.ml.common.utils.email;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class MyAuthenticator  extends Authenticator {
    private String strUser;
    private String strPwd;
    public MyAuthenticator(String user, String password) {
        this.strUser = user;
        this.strPwd = password;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(strUser, strPwd);
    }
}
package com.ml.common.utils.email;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @author
 * @describe
 * @date 2016/8/12
 */
public class RecieveMailUtil {

    private MimeMessage message;
    private Session session;
    private Folder folder;
    private Store store;
    private String mailHost="";
    private int mailPort;
    private String username="";
    private String password="";
    private String mail_auth = "";


    private Properties properties = new Properties();
    /*
     * 初始化方法
     */
    public RecieveMailUtil(String mailHost, int mailPort, String username, String password) {
        this.mailHost = mailHost;//比如qq邮箱pop.qq.com
        this.mailPort = mailPort;//995
        this.username = username;//734514801@qq.com
        this.password = password;//qq邮箱发送授权码,需要去邮箱开启并且生成授权码
        this.mail_auth = "true";

        Authenticator auth = new MyAuthenticator(username, password);
        session = Session.getDefaultInstance(properties, auth);
    }

    /**
     * 收取邮件
     */
    public void recieveEmail() {
        try {
            // Get the store
            store = session.getStore("pop3");
            store.connect(mailHost, username, password);

            /* Get folder */
            folder = store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);

            // Get directory
            Message message[] = folder.getMessages();
            for(int i=1;i<=folder.getMessageCount();i++){
                Message msg=folder.getMessage(i);
                System.out.println("========================================");
                System.out.println("邮件主题:" + msg.getSubject());
                InternetAddress[] address = (InternetAddress[]) msg.getFrom();
                String from = address[0].getAddress();//这个是发邮件人的地址
                if (from == null) {
                    from = "";
                }
                String personal = address[0].getPersonal();//这个是发邮件的人的姓名
                if (personal == null) {
                    personal = "";
                }
                String fromaddr = personal + "<" + from + ">";
                System.out.println("邮件作者:"+fromaddr);
                System.out.println("发送日期:" + msg.getSentDate());
                String type=msg.getContentType().toString().substring(0, msg.getContentType().toString().indexOf(";"));
                if(type.equals("text/html")){
                    //请你根据文件的类型来更改文件的解析方式  text/html  multipart/alternative表示复合类型
                }
//                boolean isContainerAttachment = isContainAttachment(msg);
//                System.out.println("是否包含附件:" + isContainerAttachment);
//                if (isContainerAttachment) {
                    //todo 在这里处理附件
//                    saveAttachment(msg, "d:/mailTest/");
//                }
                StringBuffer content = new StringBuffer(30);
                getMailTextContent(msg, content);
                System.out.println("邮件正文:" +  content);
//                System.out.println("------------------第" + msg.getMessageNumber() + "封邮件解析结束-------------------- ");
                System.out.println("------------------第" + msg.getMessageNumber() + "封邮件解析结束-------------------- ");

            }


        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (folder!=null){
                try {
                    folder.close(false);
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
            if(store!=null){
                try {
                    // Close connection
                    store.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }

        }
    }
    /**
     * 保存附件
     *
     * @param part    邮件中多个组合体中的其中一个组合体
     * @param destDir 附件保存目录
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void saveAttachment(Part part, String destDir) throws UnsupportedEncodingException, MessagingException,
            FileNotFoundException, IOException {
        if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();    //复杂体邮件
            //复杂体邮件包含多个邮件体
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                //获得复杂体邮件中其中一个邮件体
                BodyPart bodyPart = multipart.getBodyPart(i);
                //某一个邮件体也有可能是由多个邮件体组成的复杂体
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    InputStream is = bodyPart.getInputStream();
                    saveFile(is, destDir, decodeText(bodyPart.getFileName()));
                } else if (bodyPart.isMimeType("multipart/*")) {
                    saveAttachment(bodyPart, destDir);
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                        saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            saveAttachment((Part) part.getContent(), destDir);
        }
    }

    /**
     * 读取输入流中的数据保存至指定目录
     *
     * @param is       输入流
     * @param fileName 文件名
     * @param destDir  文件存储目录
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void saveFile(InputStream is, String destDir, String fileName)
            throws FileNotFoundException, IOException {
        BufferedInputStream bis = new BufferedInputStream(is);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(new File(destDir + fileName)));
        int len = -1;
        while ((len = bis.read()) != -1) {
            bos.write(len);
            bos.flush();
        }
        bos.close();
        bis.close();
    }

    /**
     * 文本解码
     *
     * @param encodeText 解码MimeUtility.encodeText(String text)方法编码后的文本
     * @return 解码后的文本
     * @throws UnsupportedEncodingException
     */
    public static String decodeText(String encodeText) throws UnsupportedEncodingException {
        if (encodeText == null || "".equals(encodeText)) {
            return "";
        } else {
            return MimeUtility.decodeText(encodeText);
        }
    }



    /**
     * 判断邮件中是否包含附件
     * <p>
     * //* @param msg 邮件内容
     *
     * @return 邮件中存在附件返回true,不存在返回false
     * @throws MessagingException
     * @throws IOException
     */
    public static boolean isContainAttachment(Part part) throws MessagingException, IOException {
        boolean flag = false;
        if (part.isMimeType("multipart/*")) {
            MimeMultipart multipart = (MimeMultipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    flag = true;
                } else if (bodyPart.isMimeType("multipart/*")) {
                    flag = isContainAttachment(bodyPart);
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("application") != -1) {
                        flag = true;
                    }

                    if (contentType.indexOf("name") != -1) {
                        flag = true;
                    }
                }

                if (flag) break;
            }
        } else if (part.isMimeType("message/rfc822")) {
            flag = isContainAttachment((Part) part.getContent());
        }
        return flag;
    }


    /**
     * 获得邮件文本内容
     *
     * @param part    邮件体
     * @param content 存储邮件文本内容的字符串
     * @throws MessagingException
     * @throws IOException
     */
    public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
        //如果是文本类型的附件,通过getContent方法可以取到文本内容,但这不是我们需要的结果,所以在这里要做判断
        boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
        if (part.isMimeType("text/*") && !isContainTextAttach) {
            content.append(part.getContent().toString());
        } else if (part.isMimeType("message/rfc822")) {
            getMailTextContent((Part) part.getContent(), content);
        } else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                getMailTextContent(bodyPart, content);
            }
        }
    }

    public static void main(String[] args) {
    }
}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
  • 346
  • 347
  • 348
  • 349
  • 350
  • 351
  • 352
  • 353
  • 354
  • 355
  • 356
  • 357
  • 358
  • 359
  • 360
  • 361
  • 362
  • 363
  • 364
  • 365
  • 366
  • 367
  • 368
  • 369
  • 370
  • 371
  • 372
  • 373
  • 374
  • 375
  • 376
  • 377
  • 378
  • 379
  • 380
  • 381
  • 382
  • 383
  • 384
  • 385
  • 386

四:结语

有用的话就点赞加收藏吧!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/95449?site
推荐阅读
相关标签
  

闽ICP备14008679号