重定向退回的邮件,并从退回的邮件中读取附加的文件名

时间:2015-07-02 09:34:47

标签: java email javamail

我有两个程序用于发送邮件,另一个用于阅读邮件。我的第一个问题是如何将退回的邮件重定向到除用户之外的电子邮件ID。第二个问题是,如果我有一个退回邮件,我如何阅读附加文件的名称。我已经完成了许多帖子,但似乎没有任何工作。任何帮助表示赞赏。

用于发送邮件的代码

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class bounceMail {
    String host, port, emailid,username, password;
    Properties props = System.getProperties();
    Session l_session = null;
    Session l_session1= null;

    public void sendMessage(String toEmail, String subject, String msg) {
        host = "smtp.mail.yahoo.com";
        port = "465";

        emailid = "fromemailid";
        username = "fromusername";
        password = "******";

        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        //props.put("mail.debug", "true");
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.starttls.enable","true");
        props.put("mail.smtp.socketFactory.port", port);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        //props.put("mail.smtp.from", "bounceemailid"); // not working
        l_session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });
        //l_session.setDebug(true); // Enable the debug mode

        try {
            MimeMessage message = new MimeMessage(l_session);

            //message.addFrom(InternetAddress.parse("bounceemail@yahoo.com")); // not working
            //message.setReplyTo(InternetAddress.parse("bounceemail@yahoo.com")); // not working
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
            message.setSubject(subject);
            message.setContent(msg, "text/html");
            Transport.send(message);
            System.out.println("Message Sent");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static public void main(String args[]){
        bounceMail b = new bounceMail();
        b.sendMessage("junkemailid","Test","test Mail");
    }

}

用于阅读邮件的代码

import java.util.Properties;

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.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;



public class CheckingMail {

  public static void check(String host, String storeType, String user,
  String password) 
  {
    try {

    //create properties field
    Properties properties = new Properties();
    properties.put("mail.imap.host", host);
    properties.put("mail.imap.port", "993");
    properties.put("mail.imap.starttls.enable", "true");
    Session emailSession = Session.getDefaultInstance(properties);


    Store store = emailSession.getStore("imaps");
    store.connect(host, user, password);

    //create the folder object and open it
    Folder emailFolder = store.getFolder("INBOX");
    emailFolder.open(Folder.READ_ONLY);

    // retrieve the messages from the folder in an array and print it
    Message[] messages = emailFolder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); 
    System.out.println("messages.length---" + messages.length);
    int bcnt = 0;
    for (int i = 0, n = messages.length; i < n; i++) {
       Message message = messages[i];
       if(message.getFrom()[0].toString().contains("MAILER-DAEMON")){
         bcnt++;
       }
       System.out.println("---------------------------------");
       System.out.println("Email Number " + (i + 1));
       System.out.println("Subject: " + message.getSubject());
       System.out.println("From: " + message.getFrom()[0]);

       Object content = message.getContent();
       if (content instanceof String)
           System.out.println("String");        

       if (content instanceof Multipart) {
           Multipart multipart = (Multipart) content;
           for (int j = 0; j < multipart.getCount(); j++) {
              System.out.println(multipart.getBodyPart(j).getFileName());
           }
       }

       for(int j=0;j<message.getAllRecipients().length; j++){
           System.out.println("Recipients "+j+" : " + message.getAllRecipients()[j]);
       }
       System.out.println("Date: " + message.getSentDate());
    }
    System.out.println("Bounce count : " + bcnt);

    //close the store and folder objects
    emailFolder.close(false);
    store.close();

    } catch (NoSuchProviderException e) {
       e.printStackTrace();
    } catch (MessagingException e) {
       e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
     String host = "imap.mail.yahoo.com";
     String mailStoreType = "imap";
     String username = "emailid";
     String password = "*****";
     check(host, mailStoreType, username, password);

  }

}

发送邮件时是否有可能设置自己的标题或属性,邮件反弹时可以读取?

2 个答案:

答案 0 :(得分:1)

您是否阅读过this JavaMail FAQ entry

您可以设置“mail.smtp.from”属性来设置用于返回失败消息的SMTP“信封发件人”地址,如javadocs for the com.sun.mail.smtp package中所述。

答案 1 :(得分:0)

回答第二个问题。我能够通过以下方法从退回的邮件中读取附件的名称(需要更好的方法)

BufferedReader reader = new BufferedReader(new StringReader(message.getContent().toString()));
while ((str = reader.readLine()) != null)  {
    index = str.indexOf("filename");
    if(index >-1){
        filename = str.substring(index+9); // 9 characters -> "filename=" 
        if (filename.length() > 0) System.out.println("Attachment  : " + filename);
    }
}