看了很多网上的贴子,也在Baidu上搜过.
现有两个问题.
一是收邮件时.如果原文件带附件.那么正文部份ContentType,并不是以Text/html开头
而是以.multipart/Alternative.  
163及126都是这样,并带有 boundary="----=_Part_76_1173198205.1187629828559"
请问是不是除了 自行解释用 boundary进行拆分外,别无解决办法?,附件我是收下来了.但正文部分,一直收到Null
二是发邮件.老是被拒绝..
代码如下.
package asp.email;import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.ContentType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import asp.BaseHibernateDAO;
import asp.cmp.Employee;
import asp.dao.sys.EmailDAO;
import asp.dao.sys.EmailServerDAO;/**
 * 带口令验证的邮件接收类.
 */
public class EmailReceive extends BaseHibernateDAO {
public EmailReceive() {
} public boolean receive(Employee emp,String path) {
EmailServerDAO emailServerDao = new EmailServerDAO();
String emailName = emp.getEmpEmail();
String emailPass = emp.getEmpEmailPassword();
String popServer = emailServerDao.getEmailServe(emailName, false);
System.out.println(popServer);
Store store = null;
Folder folder = null;
try {
Properties props = System.getProperties();
Session session = Session.getDefaultInstance(props,
new Email_autherticator(emailName, emailPass));
store = session.getStore("pop3");
store.connect(popServer, null, null);
folder = store.getDefaultFolder();
if (folder == null)
throw new Exception("No default folder");
folder = folder.getFolder("INBOX");
if (folder == null)
throw new Exception("No POP3 INBOX");
folder.open(Folder.READ_WRITE);
Message[] msgs = folder.getMessages();
if (msgs.length > 0) {
for (int msgNum = 0; msgNum < msgs.length; msgNum++) {
printMessage(msgs[msgNum], emp, popServer, emailName, path);// 收邮件
//msgs[msgNum].setFlag(Flags.Flag.DELETED, true);// 收完后,删除邮件
}
return true;
} else {
return false;
}
} catch (Exception ex) {
ex.printStackTrace();
return false;
} finally {
try {
if (folder != null)
folder.close(true);
if (store != null)
store.close();
} catch (Exception ex2) {
ex2.printStackTrace();
return false;
}
}
} /**
 * "printMessage()" 打印方法.
 */
public void printMessage(Message message, Employee emp, String popServer,
String emailName, String mainPath) {
try {
String from = ((InternetAddress) message.getFrom()[0])
.getPersonal();
if (from == null)
from = ((InternetAddress) message.getFrom()[0]).getAddress();// 从邮件服务器获取发件人地址
// System.out.println("FROM: " + from);
if (from.indexOf("@") < 0) {
String emailExtend = emailName
.substring(emailName.indexOf("@"));
from = from + (emailExtend); // 如果返回没有@就把邮件服务器的后缀加上
}
asp.sys.Email email = new asp.sys.Email(); // 创建邮件对象
email.setType(1); // 设置类型(1为收件)
email.setEmailForm(from); // 设置发件人Email
email.setEmailTo(emp.getEmpEmail()); // 设置收件人的地址
email.setToManId(""); // 设置收件人的ID(也就是本身登陆用户的ID)
email.setReaded(true);// 设定邮件为未读
email.setEmpId(emp.getId());
String subject = message.getSubject(); // 从邮件服务器获取邮件主题
email.setEmailTitle(subject); // 设置邮件主题
Part messagePart = message;
Object content = messagePart.getContent();
if (content instanceof Multipart) // 判断是否为多部分组成文件(有无附件)
{
Multipart mp = (Multipart) message.getContent(); // 得到
// Miltipart的数量,用于除了多个part,比如多个附件
int mpCount = mp.getCount(); // 得到附件个数
System.out.println("mpCount:"+mpCount);
String path = "";// 附件名称
for (int i = 0; i <mpCount; i++) {
BodyPart part = mp.getBodyPart(i); 
// 得到邮件附件部份
String disposition = part.getDisposition();
// 保存附件
if (disposition != null
&& disposition.equals(Part.ATTACHMENT)) {
// 得到未经处理的附件名字
String temp = part.getFileName();
String fileName = "";
if (temp.indexOf("?=") >= 0)// 表示是中文或其它国文字的附件名
{ // 除去前11位文件的头
fileName = temp.substring(11, temp.indexOf("?="));
// 转换
fileName = base64Decoder(fileName);
} else {
// 否则直接生成文件名
fileName = temp;
}
System.out.println("有附件:" + fileName);
// 得到文件的扩展名
String extendName = fileName.substring(fileName
.length() - 4, fileName.length());
String name = Math.round(Math.random() * 1000000000)
+ extendName;
path = path + "myt_youjian/emailLog/" + name + ";";
InputStream in = part.getInputStream();
FileOutputStream writer = new FileOutputStream(
new File(mainPath + "/email/emailLog/"
+ name));
byte[] bye = new byte[255];
int read = 0;
while ((read = in.read(bye)) != -1) {
writer.write(bye);
}
writer.close();
in.close();
} else {
messagePart = mp.getBodyPart(i);
}
}
email.setEmailAddPath(path);
// 下载到服务器目录并保存下载目录到("目录");
}
String contentType = messagePart.getContentType(); // 邮件类型
System.out.println("CONTENT:" + contentType);
System.out.println(messagePart.getContent());

if (contentType.startsWith("text/plain")
|| contentType.startsWith("text/html")) {
InputStream is = messagePart.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
String str = "";
String thisLine = reader.readLine();
while (thisLine != null) {
// System.out.println(thisLine);
str = str + thisLine;
thisLine = reader.readLine();
}
System.out.println("2222222222222"+str);
email.setEmailContent(str);
}
else
{

}
EmailDAO emailDao=new EmailDAO();
emailDao.save(email);
// System.out.println("-----------------------------");
} catch (Exception ex) {
ex.printStackTrace();
}
} private static String base64Decoder(String s) throws Exception// base64解码
{
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
byte[] b = decoder.decodeBuffer(s);
return (new String(b));
}

}

解决方案 »

  1.   


    ------------------------------------------------------
    package asp.email;
    import java.util.Date;
    import java.util.Properties;
    import javax.activation.DataHandler;
    import javax.activation.FileDataSource;
    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;
    import asp.dao.cmp.EmployeeDAO;
    import asp.sys.Email;
    public class EmailSend
    {
    public EmailSend()
    {
    }
    public boolean emailSend(Email email, String emailHost, String[] toList, String[] bccList, String truePath, String emailname, String emailpassword)
    {
    // 收件人
    String to = null;
    // 发件人
    String from = null;
    // 主题
    String subject = null;
    // 抄送人
    String cc = null;
    // 暗抄送
    String bcc = null;
    // mail 主机
    String mailhost = null;
    // mail 内容
    String content = null;
    // mail 附件URL
    String AffixURL = null;
    // MIME邮件对象
    MimeMessage mimeMsg = null;
    // 邮件会话对象
    Session session = null;
    String user = emailname.substring(0,emailname.indexOf("@"));
    String password = emailpassword;
    //String user = "[email protected]";
    //String password = "198585";
    System.out.println(user);
    System.out.println(password);
    try
    {
    mailhost = emailHost;// 运行nslookup 查找smtp.sohu.com
    //mailhost = "smtp.163.com";
    subject = email.getEmailTitle();
    content = email.getEmailContent();
    Properties props = System.getProperties(); // 获得系统属性
    props.put("mail.smtp.host",  mailhost); // 设置SMTP主机
    props.put("mail.smtp.auth", "true");// 设置当前的证书为真
    // 获得邮件会话对象
    session = Session.getDefaultInstance(props, new Email_autherticator(user, password));
    Transport transport=session.getTransport("smtp");
    transport.connect(mailhost,user,password);//以smtp方式登录邮箱
    // 创建MIME邮件对象
    mimeMsg = new MimeMessage(session);
    // 设置发信人
    mimeMsg.setFrom(new InternetAddress(user));
    // 设置收信人
    for (int i = 0; i < toList.length; i++)
    {
    System.out.println(toList[i]);
    mimeMsg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(toList[i]));
    }
    // 设置抄送人
    for (int i = 0; i < bccList.length; i++)
    {
    System.out.println(bccList[i]);
    mimeMsg.addRecipients(Message.RecipientType.CC, InternetAddress.parse(bccList[i]));
    }
    // 设置暗送人
    if (bcc != null)
    {
    mimeMsg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
    }
    // 设置邮件主题
    mimeMsg.setSubject(subject, "GBK");
    String path = email.getEmailAddPath();
    System.out.println(path);
    if (path != null && (path.length() > 3))// 如果有附件则加入邮件内容
    {
    // 创建邮件的多播部分
    Multipart mp = new MimeMultipart();
    // 创建邮件的第一部份为内容
    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setContent(content, "text/html;charset=gb2312");
    String language[] =
    { "gb2312", "gbk" };
    mbp1.setContentLanguage(language);
    mp.addBodyPart(mbp1);
    // 创建邮件的附件部份
    String pathArray[] = path.split(";");
    for (int i = 0; i < pathArray.length; i++)
    {
    MimeBodyPart mbp_temp = new MimeBodyPart();
    FileDataSource source = new FileDataSource(truePath + pathArray[i]);
    mbp_temp.setDataHandler(new DataHandler(source));
    System.out.println(truePath);
    System.out.println(truePath + "/" + pathArray[i]);
    mbp_temp.setFileName(pathArray[i]);
    mp.addBodyPart(mbp_temp);
    }
    mimeMsg.setContent(mp);
    }
    else
    {
    // 如果没有附件则直接设定邮件内容
    // 设置邮件内容
    // mimeMsg.setText(content, "GBK");
    mimeMsg.setContent(content, "text/html;charset=gb2312");
    String language[] =
    { "gb2312", "gbk" };
    mimeMsg.setContentLanguage(language);
    }
    // message.setContent("Hello", "text/plain");
    // 发送日期
    mimeMsg.setSentDate(new Date());
    // 发送邮件;
    transport.sendMessage(mimeMsg,mimeMsg.getAllRecipients());
    session = null;
    // System.out.println("email send!");
    return true;
    }
    catch (Exception e)
    {
    e.printStackTrace();
    return false;
    }
    }
     public static void main(String args[])
      {
     EmailSend es=new EmailSend();

        }
    }
    ---------------------------------------------------
    package asp.email;import javax.mail.*;public class Email_autherticator extends javax.mail.Authenticator {
    private String m_username = null; private String m_userpass = null; public void setUsername(String username) {
    m_username = username;
    } public void setUserpass(String userpass) {
    m_userpass = userpass;
    } public Email_autherticator() {
    super();
    } public Email_autherticator(String username, String userpass) {
    super();
    setUsername(username);
    setUserpass(userpass);
    } public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(m_username, m_userpass);
    }
    }
      

  2.   

    1.收到带附件的都是多部分的,正文是getBodyPart("0").getContent();2.一般发信通不过是因为没有加这条props.put("mail.smtp.auth","true");ps:你的代码我没有看,不好意思.
      

  3.   

    偶也来一个..注释写的很清楚!测试没有问题的.
    package com.utils;import java.util.Properties;import javax.activation.DataHandler;
    import javax.activation.FileDataSource;
    import javax.mail.Address;
    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;import sun.misc.BASE64Encoder;//import com.me.util.*;public class sendMail { private MimeMessage mimeMsg; // MIME邮件对象 private Session session; // 邮件会话对象 private Properties props; // 系统属性 private String username = ""; // smtp认证用户名和密码 private String password = ""; private Multipart mp; // Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象 public sendMail() { // setSmtpHost(getConfig.mailHost);//如果没有指定邮件服务器,就从getConfig类中获取
    createMimeMessage(); } public sendMail(String smtp) { setSmtpHost(smtp);
    createMimeMessage(); } /**
     * @param hostName
     *            String
     */
    public void setSmtpHost(String hostName) { System.out.println("设置系统属性:mail.smtp.host = " + hostName);
    if (props == null)
    props = System.getProperties(); // 获得系统属性对象 props.put("mail.smtp.host", hostName); // 设置SMTP主机 } /**
     * @return boolean
     */
    public boolean createMimeMessage() {
    try {
    System.out.println("准备获取邮件会话对象!");
    session = Session.getDefaultInstance(props, null); // 获得邮件会话对象
    } catch (Exception e) {
    System.err.println("获取邮件会话对象时发生错误!" + e);
    return false;
    } System.out.println("准备创建MIME邮件对象!"); try { mimeMsg = new MimeMessage(session); // 创建MIME邮件对象
    mp = new MimeMultipart(); return true; } catch (Exception e) { System.err.println("创建MIME邮件对象失败!" + e);
    return false;
    }
    } /**
     * @param need
     *            boolean
     */
    public void setNeedAuth(boolean need) { System.out.println("设置smtp身份认证:mail.smtp.auth = " + need);
    if (props == null)
    props = System.getProperties(); if (need) { props.put("mail.smtp.auth", "true");
    } else { props.put("mail.smtp.auth", "false");
    }
    } /**
     * @param name
     *            String
     * @param pass
     *            String
     */
    public void setNamePass(String name, String pass) {
    username = name;
    password = pass;
    } /**
     * @param mailSubject
     *            String
     * @return boolean
     */
    public boolean setSubject(String mailSubject) {
    System.out.println("设置邮件主题!");
    try {
    mimeMsg.setSubject(mailSubject);
    return true;
    } catch (Exception e) {
    System.err.println("设置邮件主题发生错误!");
    return false;
    }
    } /**
     * @param mailBody
     *            String
     */
    public boolean setBody(String mailBody) {
    try {
    BodyPart bp = new MimeBodyPart();
    bp.setContent(
    "<meta http-equiv=Content-Type content=text/html; charset=gb2312>"
    + mailBody, "text/html;charset=GB2312");
    mp.addBodyPart(bp); return true;
    } catch (Exception e) {
    System.err.println("设置邮件正文时发生错误!" + e);
    return false;
    }
    } /**
     * @param name
     *            String
     * @param pass
     *            String
     */
    public boolean addFileAffix(String filename) { System.out.println("增加邮件附件:" + filename); try {
    BodyPart bp = new MimeBodyPart();
    FileDataSource fileds = new FileDataSource(filename);

    bp.setDataHandler(new DataHandler(fileds));
    BASE64Encoder enc = new BASE64Encoder();
    bp.setFileName("=?GBK?B?"+enc.encode((fileds.getName()).getBytes())+"?="); 
    // bp.setFileName(fileds.getName()); mp.addBodyPart(bp); return true;
    } catch (Exception e) {
    System.err.println("增加邮件附件:" + filename + "发生错误!" + e);
    return false;
    }
    } /**
     * @param name
     *            String
     * @param pass
     *            String
     */
    public boolean setFrom(String from) {
    System.out.println("设置发信人!");
    try {
    mimeMsg.setFrom(new InternetAddress(from)); // 设置发信人
    return true;
    } catch (Exception e) {
    return false;
    }
    } /**
     * @param name
     *            String
     * @param pass
     *            String
     */
    public boolean setTo(String to) {
    if (to == null)
    return false; try {
    mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress
    .parse(to));
    return true;
    } catch (Exception e) {
    return false;
    } } /**
     * @param name
     *            String
     * @param pass
     *            String
     */
    public boolean setCopyTo(String copyto) {
    if (copyto == null)
    return false;
    try {
    mimeMsg.setRecipients(Message.RecipientType.CC,
    (Address[]) InternetAddress.parse(copyto));
    return true;
    } catch (Exception e) {
    return false;
    }
    } /**
     * @param name
     *            String
     * @param pass
     *            String
     */
    public boolean sendout() {
    try {
    mimeMsg.setContent(mp);
    mimeMsg.saveChanges();
    System.out.println("正在发送邮件...."); Session mailSession = Session.getInstance(props, null);
    Transport transport = mailSession.getTransport("smtp");
    transport.connect((String) props.get("mail.smtp.host"), username,
    password);
    transport.sendMessage(mimeMsg, mimeMsg
    .getRecipients(Message.RecipientType.TO)); System.out.println("发送邮件成功!");
    transport.close(); return true;
    } catch (Exception e) { System.err.println("邮件发送失败!" + e);
    return false;
    } } /**
     * Just do it as this
     */
    public static void main(String[] args) { // mailbody->发送 的邮件 内容
    String mailbody = "<meta http-equiv=Content-Type content=text/html; charset=gb2312>"
    + "<div align=center><table border=1><tr><td>姓名</td><td>性别</td></tr><tr><td><font color=blue>大白菜</font></td><td>120</td></tr></table></div>"; // themail表示要发送到那个smtp上去(转发的地位)
    sendMail themail = new sendMail("smtp.sohu.com"); // 是否要验证用户身份
    themail.setNeedAuth(true); // 邮件标题
    if (themail.setSubject("大白菜say hello!") == false)
    return;
    if (themail.setBody(mailbody) == false)
    return; // 指明发送到那个用户
    if (themail.setTo("[email protected]") == false)
    return; // 显示是谁发来得
    if (themail.setFrom("[email protected]") == false)
    return;
    // 表明要带的附件
    if (themail.addFileAffix("") == false)
    return;
    themail.setNamePass("rightlinker_test", "123123"); if (themail.sendout() == false)
    return;
    }
    }