如何使用JavaMail删除QQ邮件服务器上的邮件

如何使用JavaMail删除QQ邮件服务器上的邮件,第1张

JavaMail是提供给开发者处理电子邮件相关的编程接口。它是Sun发布的用来处理email的API。可以方便地执行一些常用的邮件传输。

如果需要使用JavaMail编程来实现删除QQ邮件服务器上的邮件,可以参考以下代码,在调用deleteMessages方法时,只需要传入邮件服务器地址、端口、邮箱登录用户名、登录密码以及需要删除的邮件主题五个参数即可:

package com.what21.network.mail

 

import java.util.Properties

 

import javax.mail.Flags

import javax.mail.Folder

import javax.mail.Message

import javax.mail.MessagingException

import javax.mail.NoSuchProviderException

import javax.mail.Session

import javax.mail.Store

  

public class EmailMessageRemover {

 

    /**

     * 删除主题中包含subjectToDelete字符串的所有邮件

     * 

     * @param 邮箱服务器地址

     * @param 邮箱服务器端口

     * @param 登录用户名

     * @param 登录密码

     * @param 如果邮件主题包含这个字符串就会对其进行删除操作

     */

    public void deleteMessages(String host, String port, String userName,

            String password, String subjectToDelete) {

        Properties properties = new Properties()

 

        // 邮箱服务器配置

        properties.put("mail.imap.host", host)

        properties.put("mail.imap.port", port)

 

        // SSL 连接配置

        properties.setProperty("mail.imap.socketFactory.class",

                "javax.net.ssl.SSLSocketFactory")

        properties.setProperty("mail.imap.socketFactory.fallback", "false")

        properties.setProperty("mail.imap.socketFactory.port",

                String.valueOf(port))

 

        Session session = Session.getDefaultInstance(properties)

 

        try {

            // 连接邮箱服务器

            Store store = session.getStore("imap")

            store.connect(userName, password)

 

            // 打开收件箱

            Folder folderInbox = store.getFolder("INBOX")

            folderInbox.open(Folder.READ_WRITE)

 

            // 从服务器获取新邮件

            Message[] arrayMessages = folderInbox.getMessages()

 

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

                Message message = arrayMessages[i]

                String subject = message.getSubject()

                if (subject.contains(subjectToDelete)) {

                    //给需要删除的邮件打上标签

                    message.setFlag(Flags.Flag.DELETED, true)

                    System.out.println("Marked DELETE for message: " + subject)

                }

 

            }

 

            // 删除指定的邮件

            boolean expunge = true

            folderInbox.close(expunge)

 

            // another way:

            // folderInbox.expunge()

            // folderInbox.close(false)

 

            // 断开连接

            store.close()

        } catch (NoSuchProviderException ex) {

            System.out.println("No provider.")

            ex.printStackTrace()

        } catch (MessagingException ex) {

            System.out.println("Could not connect to the message store.")

            ex.printStackTrace()

        }

    }

 

    /**

     * 测试-Gmail邮箱

     * protocol.

     */

    public static void main(String[] args) {

        String host = "imap.gmail.com"

        String port = "993"

        String userName = "your_email"

        String password = "your_password"

        EmailMessageRemover remover = new EmailMessageRemover()

 

        String subjectToDelete = "Newsletter"

        remover.deleteMessages(host, port, userName, password, subjectToDelete)

 

    }

}

当javamail使用smtp服务发送邮件时,当你把邮件发送到smtp服务器的时候,你只能得到已经发送到smtp的队列中的状态,但是邮件服务器是否能发送成功,你是得不到的。就是说,你不能保证邮件发送一定成功。 这就取决于SMTP协议的内容传输了。

但是SMTP协议如果传输失败,是会报错的。SMTP由TCP提供的可靠的数据传输服务把邮件消息从发信人的邮件服务器传送到收信人的邮件服务器。

所以我们可以认为当我们调用JavaMail发送邮件时,如果程序没有报错则表示邮件发送成功。

SMTP通常有两种工作模式:发送SMTP和接收SMTP。

具体工作方式为:发送SMTP在接到用户的邮件请求后,判断此邮件是否为本地邮件,若是直接投送到用户的邮箱,否则向dns查询远端邮件服务器的 MX纪录,并建立与远端接收SMTP之间的一个双向传送通道,此后SMTP命令由发送SMTP发出,由接收SMTP接收,而应答则反方面传送。一旦传送通 道建立,SMTP发送者发送MAIL命令指明邮件发送者。如果SMTP接收者可以接收邮件则返回OK应答。SMTP发送者再发出RCPT命令确认邮件是否 接收到。如果SMTP接收者接收,则返回OK应答;如果不能接收到,则发出拒绝接收应答(但不中止整个邮件操作),双方将如此重复多次。当接收者收到全部 邮件后会接收到特别的序列,如果接收者成功处理了邮件,则返回OK应答即可。

package com.gwxc.hz.mail.demo

import java.io.BufferedInputStream

import java.io.BufferedOutputStream

import java.io.File

import java.io.FileOutputStream

import java.io.InputStream

import java.text.SimpleDateFormat

import java.util.Date

import java.util.Properties

import javax.mail.BodyPart

import javax.mail.Flags

import javax.mail.Folder

import javax.mail.Message

import javax.mail.MessagingException

import javax.mail.Multipart

import javax.mail.NoSuchProviderException

import javax.mail.Part

import javax.mail.Session

import javax.mail.Store

import javax.mail.URLName

import javax.mail.internet.InternetAddress

import javax.mail.internet.MimeMessage

import javax.mail.internet.MimeUtility

public class ReciveOneMail {

/**

* 有一封邮件就需要建立一个ReciveMail对象

*/

private MimeMessage mimeMessage = null

private String saveAttachPath = ""// 附件下载后的存放目录

private StringBuffer bodytext = new StringBuffer()// 存放邮件内容

private String dateformat = "yy-MM-dd HH:mm"// 默认的日前显示格式

public ReciveOneMail(MimeMessage mimeMessage) {

this.mimeMessage = mimeMessage

}

public void setMimeMessage(MimeMessage mimeMessage) {

this.mimeMessage = mimeMessage

}

/**

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

*/

public String getFrom() throws Exception {

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 = personal + "<" + from + ">"

return fromaddr

}

/**

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

*/

public String getMailAddress(String type) throws Exception {

String mailaddr = ""

String addtype = type.toUpperCase()

InternetAddress[] address = null

if (addtype.equals("TO") || addtype.equals("CC")

|| addtype.equals("BCC")) {

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 (address != null) {

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

String email = address[i].getAddress()

if (email == null)

email = ""

else {

email = MimeUtility.decodeText(email)

}

String personal = address[i].getPersonal()

if (personal == null)

personal = ""

else {

personal = MimeUtility.decodeText(personal)

}

String compositeto = personal + "<" + email + ">"

mailaddr += "," + compositeto

}

mailaddr = mailaddr.substring(1)

}

} else {

throw new Exception("Error emailaddr type!")

}

return mailaddr

}

/**

* 获得邮件主题

*/

public String getSubject() throws MessagingException {

String subject = ""

try {

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

if (subject == null)

subject = ""

} catch (Exception exce) {

}

return subject

}

/**

* 获得邮件发送日期

*/

public String getSentDate() throws Exception {

Date sentdate = mimeMessage.getSentDate()

SimpleDateFormat format = new SimpleDateFormat(dateformat)

return format.format(sentdate)

}

/**

* 获得邮件正文内容

*/

public String getBodyText() {

return bodytext.toString()

}

/**

* 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件 主要是根据MimeType类型的不同执行不同的操作,一步一步的解析

*/

public void getMailContent(Part part) throws Exception {

String contenttype = part.getContentType()

int nameindex = contenttype.indexOf("name")

boolean conname = false

if (nameindex != -1)

conname = true

System.out.println("CONTENTTYPE: " + contenttype)

if (part.isMimeType("text/plain") &&!conname) {

bodytext.append((String) part.getContent())

} else if (part.isMimeType("text/html") &&!conname) {

bodytext.append((String) part.getContent())

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

Multipart multipart = (Multipart) part.getContent()

int counts = multipart.getCount()

for (int i = 0i <countsi++) {

getMailContent(multipart.getBodyPart(i))

}

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

getMailContent((Part) part.getContent())

} else {

}

}

/**

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

*/

public boolean getReplySign() throws MessagingException {

boolean replysign = false

String needreply[] = mimeMessage

.getHeader("Disposition-Notification-To")

if (needreply != null) {

replysign = true

}

return replysign

}

/**

* 获得此邮件的Message-ID

*/

public String getMessageId() throws MessagingException {

return mimeMessage.getMessageID()

}

/**

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

*/

public boolean isNew() throws MessagingException {

boolean isnew = false

Flags flags = ((Message) mimeMessage).getFlags()

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

System.out.println("flags's length: " + flag.length)

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

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

isnew = true

System.out.println("seen Message.......")

break

}

}

return isnew

}

/**

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

*/

public boolean isContainAttach(Part part) throws Exception {

boolean attachflag = false

String contentType = part.getContentType()

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

Multipart mp = (Multipart) part.getContent()

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

BodyPart mpart = mp.getBodyPart(i)

String disposition = mpart.getDisposition()

if ((disposition != null)

&&((disposition.equals(Part.ATTACHMENT)) || (disposition

.equals(Part.INLINE))))

attachflag = true

else if (mpart.isMimeType("multipart/*")) {

attachflag = isContainAttach((Part) mpart)

} else {

String contype = mpart.getContentType()

if (contype.toLowerCase().indexOf("application") != -1)

attachflag = true

if (contype.toLowerCase().indexOf("name") != -1)

attachflag = true

}

}

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

attachflag = isContainAttach((Part) part.getContent())

}

return attachflag

}

/**

* 【保存附件】

*/

public void saveAttachMent(Part part) throws Exception {

String fileName = ""

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

Multipart mp = (Multipart) part.getContent()

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

BodyPart mpart = mp.getBodyPart(i)

String disposition = mpart.getDisposition()

if ((disposition != null)

&&((disposition.equals(Part.ATTACHMENT)) || (disposition

.equals(Part.INLINE)))) {

fileName = mpart.getFileName()

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

fileName = MimeUtility.decodeText(fileName)

}

saveFile(fileName, mpart.getInputStream())

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

saveAttachMent(mpart)

} else {

fileName = mpart.getFileName()

if ((fileName != null)

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

fileName = MimeUtility.decodeText(fileName)

saveFile(fileName, mpart.getInputStream())

}

}

}

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

saveAttachMent((Part) part.getContent())

}

}

/**

* 【设置附件存放路径】

*/

public void setAttachPath(String attachpath) {

this.saveAttachPath = attachpath

}

/**

* 【设置日期显示格式】

*/

public void setDateFormat(String format) throws Exception {

this.dateformat = format

}

/**

* 【获得附件存放路径】

*/

public String getAttachPath() {

return saveAttachPath

}

/**

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

*/

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

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

String storedir = getAttachPath()

String separator = ""

if (osName == null)

osName = ""

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

separator = "\\"

if (storedir == null || storedir.equals(""))

storedir = "c:\\tmp"

} else {

separator = "/"

storedir = "/tmp"

}

File storefile = new File(storedir + separator + fileName)

System.out.println("storefile's path: " + storefile.toString())

// for(int i=0storefile.exists()i++){

// storefile = new File(storedir+separator+fileName+i)

// }

BufferedOutputStream bos = null

BufferedInputStream bis = null

try {

bos = new BufferedOutputStream(new FileOutputStream(storefile))

bis = new BufferedInputStream(in)

int c

while ((c = bis.read()) != -1) {

bos.write(c)

bos.flush()

}

} catch (Exception exception) {

exception.printStackTrace()

throw new Exception("文件保存失败!")

} finally {

bos.close()

bis.close()

}

}

public static void main(String[] args) throws Exception {

Properties props = System.getProperties()

props.put("mail.smtp.host", "smtp.163.com")

props.put("mail.smtp.auth", "true")

Session session = Session.getDefaultInstance(props, null)

URLName urln = new URLName("pop3", "pop3.163.com", 110, null,

"dt_cj2004", "abcdefghij")

Store store = session.getStore(urln)

store.connect()

Folder folder = store.getFolder("spool")

//Folder folder = store.getFullName()

folder.open(Folder.READ_ONLY)

//System.out.println(folder.getNewMessageCount())

Message message[] = folder.getMessages()

System.out.println("Messages's length: " + message.length)

ReciveOneMail pmm = null

/*

for (int i = 0i <message.lengthi++) {

System.out.println("======================")

pmm = new ReciveOneMail((MimeMessage) message[i])

System.out

.println("Message " + i + " subject: " + pmm.getSubject())

System.out.println("Message " + i + " sentdate: "

+ pmm.getSentDate())

System.out.println("Message " + i + " replysign: "

+ pmm.getReplySign())

System.out.println("Message " + i + " hasRead: " + pmm.isNew())

System.out.println("Message " + i + " containAttachment: "

+ pmm.isContainAttach((Part) message[i]))

System.out.println("Message " + i + " form: " + pmm.getFrom())

System.out.println("Message " + i + " to: "

+ pmm.getMailAddress("to"))

System.out.println("Message " + i + " cc: "

+ pmm.getMailAddress("cc"))

System.out.println("Message " + i + " bcc: "

+ pmm.getMailAddress("bcc"))

pmm.setDateFormat("yy年MM月dd日 HH:mm")

System.out.println("Message " + i + " sentdate: "

+ pmm.getSentDate())

System.out.println("Message " + i + " Message-ID: "

+ pmm.getMessageId())

// 获得邮件内容===============

pmm.getMailContent((Part) message[i])

System.out.println("Message " + i + " bodycontent: \r\n"

+ pmm.getBodyText())

pmm.setAttachPath("c:\\")

pmm.saveAttachMent((Part) message[i])

}

*/

}

}

package com.gwxc.hz.mail.demo

import java.util.Properties

import javax.activation.DataHandler

import javax.activation.FileDataSource

import javax.mail.BodyPart

import javax.mail.Message

import javax.mail.Multipart

import javax.mail.Session

import javax.mail.Transport

import javax.mail.internet.InternetAddress

import javax.mail.internet.MimeBodyPart

import javax.mail.internet.MimeMessage

import javax.mail.internet.MimeMultipart

public class MyMailTest {

/**

* @param args

*/

public static void main(String[] args) throws Exception {

// 会话===========================

Properties props = System.getProperties()

props.put("mail.smtp.host", "smtp.163.com")

props.put("mail.smtp.auth", "true")// 需要验证

Session session = Session.getDefaultInstance(props, null)

// msg 设置=======================

MimeMessage mimeMsg = new MimeMessage(session)

// 设置标题

mimeMsg.setSubject("标题test")

// 设置内容----begin

Multipart mp = new MimeMultipart()

// 添加文本

BodyPart bp1 = new MimeBodyPart()

bp1.setContent("文本内容", "text/htmlcharset=GB2312")

mp.addBodyPart(bp1)

// 添加附件

BodyPart bp2 = new MimeBodyPart()

FileDataSource fileds = new FileDataSource("c:\\boot.ini")

bp2.setDataHandler(new DataHandler(fileds))

bp2.setFileName(fileds.getName())

mp.addBodyPart(bp2)

mimeMsg.setContent(mp)

// 设置内容----end

mimeMsg.setFrom(new InternetAddress("xiangzhengyan@163.com"))

mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress

.parse("xiangyh@asiacom-online.com"))

mimeMsg.saveChanges()

// 传输==================================

Transport transport = session.getTransport("smtp")

transport.connect((String) props.get("mail.smtp.host"),

"xiangzhengyan", "pass")

transport.sendMessage(mimeMsg, mimeMsg

.getRecipients(Message.RecipientType.TO))

transport.close()

}

}


欢迎分享,转载请注明来源:夏雨云

原文地址:https://www.xiayuyun.com/zonghe/247786.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-13
下一篇2023-04-13

发表评论

登录后才能评论

评论列表(0条)

    保存