好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java实现读取163邮箱,qq邮箱的邮件内容

通过使用java mail来实现读取163邮箱,qq邮箱的邮件内容。

1.代码实现

创建springboot项目,引入依赖包

?

1

2

3

4

5

<!--mail-->

        < dependency >

            < groupId >org.springframework.boot</ groupId >

            < artifactId >spring-boot-starter-mail</ artifactId >

        </ dependency >

实现类

?

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

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

import com.sun.mail.imap.IMAPFolder;

import com.sun.mail.imap.protocol.IMAPProtocol;

import org.apache.tomcat.util.http.fileupload.IOUtils;

import org.springframework.util.ObjectUtils;

 

import javax.mail.*;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeUtility;

import java.io.*;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.*;

 

public class ShowMail {

 

     public static String NORM_DATETIME_PATTERN = "yyyy-MM-dd hh:mm:ss" ;

     private MimeMessage mimeMessage;

     /**

      * 附件下载后的存放目录

      */

     private String saveAttachPath = "" ;

     /**

      * 存放邮件内容的StringBuffer对象

      */

     private StringBuffer bodyText = new StringBuffer();

 

     /**

      * 构造函数,初始化一个MimeMessage对象

      *

      * @param mimeMessage

      */

     public ShowMail(MimeMessage mimeMessage) {

         this .mimeMessage = mimeMessage;

     }

 

     /**

      * 获得发件人的地址和姓名

      *

      * @return

      * @throws MessagingException

      */

     public String getFrom() throws MessagingException {

         InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();

         String from = address[ 0 ].getAddress();

         if (from == null ) {

             from = "" ;

         }

         String personal = address[ 0 ].getPersonal();

 

         if (personal == null ) {

             personal = "" ;

         }

 

         String fromAddr = null ;

         if (personal != null || from != null ) {

             fromAddr = personal + "<" + from + ">" ;

         }

         return fromAddr;

     }

 

     /**

      * 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同

      *

      * @param type "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址

      * @return

      * @throws MessagingException

      * @throws UnsupportedEncodingException

      */

     public String getMailAddress(String type) throws MessagingException, UnsupportedEncodingException {

         if (ObjectUtils.isEmpty(type)) {

             return "" ;

         }

 

         String addType = type.toUpperCase();

 

         if (!addType.equals( "TO" ) && !addType.equals( "CC" ) && !addType.equals( "BCC" )) {

             return "" ;

         }

         InternetAddress[] address;

 

         if (addType.equals( "TO" )) {

             address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.TO);

         } else if (addType.equals( "CC" )) {

             address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.CC);

         } else {

             address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.BCC);

         }

 

         if (ObjectUtils.isEmpty(address)) {

             return "" ;

         }

         StringBuilder mailAddr = new StringBuilder();

         String emailAddr;

         String personal;

         for ( int i = 0 ; i < address.length; i++) {

             emailAddr = address[i].getAddress();

             if (emailAddr == null ) {

                 emailAddr = "" ;

             } else {

                 emailAddr = MimeUtility.decodeText(emailAddr);

             }

             personal = address[i].getPersonal();

             if (personal == null ) {

                 personal = "" ;

             } else {

                 personal = MimeUtility.decodeText(personal);

             }

             mailAddr.append( "," ).append(personal).append( "<" ).append(emailAddr).append( ">" );

         }

         return mailAddr.toString().substring( 1 );

     }

 

     /**

      * 获得邮件主题

      *

      * @return

      * @throws MessagingException

      * @throws UnsupportedEncodingException

      */

     public String getSubject() throws MessagingException, UnsupportedEncodingException {

         String subject = MimeUtility.decodeText(mimeMessage.getSubject());

         if (subject == null ) {

             subject = "" ;

         }

         return subject;

     }

 

     /**

      * 获得邮件发送日期

      *

      * @return

      * @throws MessagingException

      */

     public String getSentDate() throws MessagingException {

         Date sentDate = mimeMessage.getSentDate();

         SimpleDateFormat format = new SimpleDateFormat(NORM_DATETIME_PATTERN);

         return format.format(sentDate);

     }

 

     /**

      * 获得邮件正文内容

      *

      * @return

      */

     public String getBodyText() {

         return bodyText.toString();

     }

 

     /**

      * 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件

      * 主要是根据MimeType类型的不同执行不同的操作,一步一步的解析

      * @param part

      * @throws MessagingException

      * @throws IOException

      */

     public void getMailContent(Part part) throws MessagingException, IOException {

 

         String contentType = part.getContentType();

 

         int nameIndex = contentType.indexOf( "name" );

 

         boolean conName = false ;

 

         if (nameIndex != - 1 ) {

             conName = true ;

         }

 

         if (part.isMimeType( "text/plain" ) && conName == false ) {

             bodyText.append((String) part.getContent());

         } else if (part.isMimeType( "text/html" ) && conName == false ) {

             bodyText.append((String) part.getContent());

         } else if (part.isMimeType( "multipart/*" )) {

             Multipart multipart = (Multipart) part.getContent();

             int counts = multipart.getCount();

             for ( int i = 0 ; i < counts; i++) {

                 this .getMailContent(multipart.getBodyPart(i));

             }

         } else if (part.isMimeType( "message/rfc822" )) {

             this .getMailContent((Part) part.getContent());

         }

     }

 

     /**

      * 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"

      *

      * @return

      * @throws MessagingException

      */

     public boolean getReplySign() throws MessagingException {

 

         boolean replySign = false ;

 

         String needReply[] = mimeMessage.getHeader( "Disposition-Notification-To" );

 

         if (needReply != null ) {

             replySign = true ;

         }

         return replySign;

     }

 

     /**

      * 判断此邮件是否已读,如果未读返回false,反之返回true

      *

      * @return

      * @throws MessagingException

      */

     public boolean isNew() throws MessagingException {

         boolean isNew = false ;

         Flags flags = mimeMessage.getFlags();

         Flags.Flag[] flag = flags.getSystemFlags();

         for ( int i = 0 ; i < flag.length; i++) {

             if (flag[i] == Flags.Flag.SEEN) {

                 isNew = true ;

             }

         }

         return isNew;

     }

 

     /**

      * 判断此邮件是否包含附件

      *

      * @param part

      * @return

      * @throws MessagingException

      * @throws IOException

      */

     public boolean isContainAttach(Part part) throws MessagingException, IOException {

         boolean attachFlag = false ;

         if (part.isMimeType( "multipart/*" )) {

             Multipart mp = (Multipart) part.getContent();

             BodyPart mPart;

             String conType;

             for ( int i = 0 ; i < mp.getCount(); i++) {

                 mPart = mp.getBodyPart(i);

                 String disposition = mPart.getDisposition();

                 if (Part.ATTACHMENT.equals(disposition) || Part.INLINE.equals(disposition)) {

                     attachFlag = true ;

                 } else if (mPart.isMimeType( "multipart/*" )) {

                     attachFlag = this .isContainAttach(mPart);

                 } else {

                     conType = mPart.getContentType();

                     if (conType.toLowerCase().indexOf( "application" ) != - 1 || conType.toLowerCase().indexOf( "name" ) != - 1 ){

                         attachFlag = true ;

                     }

                 }

             }

         } else if (part.isMimeType( "message/rfc822" )) {

             attachFlag = isContainAttach((Part) part.getContent());

         }

         return attachFlag;

     }

 

     /**

      * 保存附件

      *

      * @param part

      * @throws MessagingException

      * @throws IOException

      */

     public void saveAttachMent(Part part) throws MessagingException, IOException {

         String fileName;

         if (part.isMimeType( "multipart/*" )) {

             Multipart mp = (Multipart) part.getContent();

             BodyPart mPart;

             for ( int i = 0 ; i < mp.getCount(); i++) {

                 mPart = mp.getBodyPart(i);

                 String disposition = mPart.getDisposition();

                 if (Part.ATTACHMENT.equals(disposition) || Part.INLINE.equals(disposition)) {

                     fileName = mPart.getFileName();

                     if ( null != fileName && fileName.toLowerCase().indexOf( "gb2312" ) != - 1 ) {

                         fileName = MimeUtility.decodeText(fileName);

                     }

                     this .saveFile(fileName, mPart.getInputStream());

                 } else if (mPart.isMimeType( "multipart/*" )) {

                     this .saveAttachMent(mPart);

                 } else {

                     fileName = mPart.getFileName();

                     if ((fileName != null ) && (fileName.toLowerCase().indexOf( "GB2312" ) != - 1 )) {

                         fileName = MimeUtility.decodeText(fileName);

                         this .saveFile(fileName, mPart.getInputStream());

                     }

                 }

             }

         } else if (part.isMimeType( "message/rfc822" )) {

             this .saveAttachMent((Part) part.getContent());

         }

     }

 

     /**

      * 设置附件存放路径

      *

      * @param attachPath

      */

     public void setAttachPath(String attachPath) {

         this .saveAttachPath = attachPath;

     }

 

     /**

      * 获得附件存放路径

      *

      * @return

      */

     public String getAttachPath() {

         return saveAttachPath;

     }

 

     /**

      * 真正的保存附件到指定目录里

      *

      * @param fileName

      * @param in

      * @throws IOException

      */

     private void saveFile(String fileName, InputStream in) throws IOException {

         String osName = System.getProperty( "os.name" );

         String storeDir = this .getAttachPath();

         if ( null == osName) {

             osName = "" ;

         }

         if (osName.toLowerCase().indexOf( "win" ) != - 1 ) {

             if (ObjectUtils.isEmpty(storeDir))

                 storeDir = "C:\\tmp" ;

         } else {

             storeDir = "/tmp" ;

         }

//        fileName=fileName.replace("=?", "");

//        fileName=fileName.replace("?=", "");

//        fileName = fileName.substring(fileName.length() - 6, fileName.length());

         FileOutputStream fos = new FileOutputStream( new File(storeDir + File.separator + fileName));

         IOUtils.copy(in, fos);

         IOUtils.closeQuietly(fos);

         IOUtils.closeQuietly(in);

     }

 

     /**

      * 获取163邮箱信息

      *

      * @param host

      * @param username

      * @param password

      * @param protocol

      * @return

      * @throws MessagingException

      */

     public static Message[] getWEMessage(String host, String username, String password, String protocol) throws MessagingException {

         //创建属性对象

         Properties props = System.getProperties();

         props.setProperty( "mail.store.protocol" , protocol);

         //创建会话

         Session session = Session.getDefaultInstance(props, null );

         //存储对象

         Store store = session.getStore(protocol);

         //连接

         store.connect(host, username, password);

         //创建目录对象

         Folder folder = store.getFolder( "INBOX" );

         if (folder instanceof IMAPFolder) {

             IMAPFolder imapFolder = (IMAPFolder)folder;

             //javamail中使用id命令有校验checkOpened, 所以要去掉id方法中的checkOpened();

             imapFolder.doCommand( new IMAPFolder.ProtocolCommand() {

                 public Object doCommand(IMAPProtocol p) throws com.sun.mail.iap.ProtocolException {

                     p.id( "FUTONG" );

                     return null ;

                 }

             });

         }

         if (folder != null ) {

             folder.open(Folder.READ_WRITE);

         }

         return folder.getMessages();

     }

 

     /**

      * 获取qq邮箱信息

      *

      * @param host

      * @param username

      * @param password

      * @param protocol

      * @return

      * @throws MessagingException

      */

     public static Message[] getQQMessage(String host, String username, String password, String protocol) throws MessagingException {

         //创建属性对象

         Properties props = new Properties();

         props.put( "mail.store.protocol" , protocol);

         //创建会话

         Session session = Session.getDefaultInstance(props, null );

         //存储对象

         Store store = session.getStore(protocol);

         //连接

         store.connect(host,username,password);

         //创建目录对象

         Folder folder = store.getFolder( "Inbox" );

         if (folder != null ) {

             folder.open(Folder.READ_WRITE);

         }

         return folder.getMessages();

     }

 

     /**

      * 过滤邮箱信息

      *

      * @param messages

      * @param fromMail 只读取该邮箱发来的邮件,如果为空则不过滤

      * @param startDate 只读取该日期以后的邮件,如果为空则不过滤

      * @return

      * @throws MessagingException

      */

     public static List<Message> filterMessage(Message[] messages, String fromMail, String startDate) throws MessagingException, ParseException {

         List<Message> messageList = new ArrayList<>();

         if (ObjectUtils.isEmpty(messages)) {

             return messageList;

         }

         boolean isEnptyFromMail = ObjectUtils.isEmpty(fromMail);

         boolean isEnptyStartDate = ObjectUtils.isEmpty(startDate);

         if (isEnptyFromMail && isEnptyStartDate) {

             return Arrays.asList(messages);

         }

 

         String from;

         for (Message message: messages) {

             from = null ;

             if (message.getFrom() != null ) {

                 from = (message.getFrom()[ 0 ]).toString();

             }

             if (isEnptyFromMail) {

                 if (message.getSentDate() != null && new SimpleDateFormat(NORM_DATETIME_PATTERN).parse(startDate).getTime() > message.getSentDate().getTime()) {

                     continue ;

                 }

             } else if ( null != from && from.contains(fromMail)) {

                 if (!isEnptyStartDate && new SimpleDateFormat(NORM_DATETIME_PATTERN).parse(startDate).getTime() > message.getSentDate().getTime()) {

                     continue ;

                 }

             } else {

                 continue ;

             }

             messageList.add(message);

         }

         return messageList;

     }

 

     /**

      * 打印邮件

      *

      * @param messageList

      * @throws IOException

      * @throws MessagingException

      */

     public static void printMailMessage(List<Message> messageList) throws IOException, MessagingException {

         System.out.println( "邮件数量:" + messageList.size());

         ShowMail re;

         Message message;

         for ( int i = 0 , leng = messageList.size(); i < leng; i++) {

             message = messageList.get(i);

             re = new ShowMail((MimeMessage) message);

             System.out.println( "邮件【" + i + "】主题:" + re.getSubject());

             System.out.println( "邮件【" + i + "】发送时间:" + re.getSentDate());

             System.out.println( "邮件【" + i + "】是否需要回复:" + re.getReplySign());

             System.out.println( "邮件【" + i + "】是否已读:" + re.isNew());

             System.out.println( "邮件【" + i + "】是否包含附件:" + re.isContainAttach( message));

             System.out.println( "邮件【" + i + "】发送人地址:" + re.getFrom());

             System.out.println( "邮件【" + i + "】收信人地址:" + re.getMailAddress( "to" ));

             System.out.println( "邮件【" + i + "】抄送:" + re.getMailAddress( "cc" ));

             System.out.println( "邮件【" + i + "】暗抄:" + re.getMailAddress( "bcc" ));

             System.out.println( "邮件【" + i + "】发送时间:" + re.getSentDate());

             System.out.println( "邮件【" + i + "】邮件ID:" + ((MimeMessage) message).getMessageID());

             re.getMailContent(message);

             System.out.println( "邮件【" + i + "】正文内容:\r\n" + re.getBodyText());

             re.setAttachPath( "D:\\Download\\mailFile\\" );

             re.saveAttachMent(message);

         }

     }

 

     public static void main(String[] args) throws MessagingException, IOException, ParseException {

         //163登录信息

         //邮件服务器

         String host = "mail.xx测试数据" ;

         //邮箱账号

         String username = "xx" ;

         //授权码

         String password = "yy" ;

         //协议

         String protocol = "imaps" ;

         //只读取该邮箱发来的邮件

         String fromMail = null ;

         //只读取该日期以后的邮件

         String startDate = null ;

         List<Message> messageList = filterMessage(getWEMessage(host, username, password, protocol), fromMail, startDate);

         printMailMessage(messageList);

 

         //qq登录信息

         String host2 = "imap.qq测试数据" ;

         String username2 = "xx" ;

         String password2 = "yy" ;

        // String protocol2 = "imaps";

         String protocol2 = "pop3" ;

         String fromMail2 = null ;

         String startDate2 = null ;

         List<Message> messageList2 = filterMessage(getQQMessage(host2, username2, password2, protocol2), fromMail2, startDate2);

         printMailMessage(messageList2);

     }

 

}

2.配置授权码

163邮箱:

qq邮箱:

3.实现效果:

运行main方法,查看控制台:

?

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

邮件数量:xx

邮件【0】主题:欢迎您使用xx邮箱!

邮件【0】发送时间:xx

邮件【0】是否需要回复: false

邮件【0】是否已读: true

邮件【0】是否包含附件: false

邮件【0】发送人地址:xx

邮件【0】收信人地址:xx

邮件【0】抄送:

邮件【0】暗抄:

邮件【0】发送时间:xx

邮件【0】邮件ID:xx

邮件【0】正文内容:

<!DOCTYPE html>

<html lang= "en" >

< head >

     <meta charset= "UTF-8" >

     <meta name= "viewport" content= "width=device-width, initial-scale=1.0" >

     <meta http-equiv= "X-UA-Compatible" content= "ie=edge" >

     <title>欢迎使用< /title >

     <style>

         body, div, p, img {

             padding: 0;

             margin: 0;

             font-family: 'Microsoft Yahei' , "PingFang SC" , "Hiragino Sans GB" , "wenquanyi micro hei" , Arial, Helvetica, "STHeiti" , sans-serif;

         }

         .contain {

             width: 700px;

             margin: 0 auto;

             font-size: 0;

         }

         .wrap {

             position: relative;

         }

         .wrap .welcome {

             position: absolute;

             width: 290px;

             left: 75px;

             top : 100px;

             font-size: 18px;

             color: #fff;

             line-height: 32px;

             font-weight: 500;

         }

         .wrap .welcome p.indentation {

             font-size: 16px;

             font-weight: normal;

         }

         .wrap a {

             position: absolute;

             display: block;

             width: 104px;

             height: 39px;

         }

         .wrap a.mobile{

             left: 501px;

             top : 434px;

         }

         .wrap a.pc{

             left: 501px;

             top : 485px;

         }

     < /style >

< /head >

<body>

     <div class= "contain" >

         <div class= "wrap" >

             <div class= "welcome" >

                 <p class= "indentation-title" >尊敬的xx:< /p >

                 <p class= "indentation" >您好,您的邮箱已开通。< /p >

             < /div >

         < /div >

     < /div >

< /body >

< /html >

到此这篇关于Java实现读取163邮箱,qq邮箱的邮件内容的文章就介绍到这了,更多相关Java读取邮箱邮件内容内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/weixin_39220472/article/details/122745908

查看更多关于Java实现读取163邮箱,qq邮箱的邮件内容的详细内容...

  阅读:17次