码迷,mamicode.com
首页 > 编程语言 > 详细

JavaMail直接发送邮件

时间:2016-05-28 17:42:43      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:

 一般用JavaMail发送邮件都需要先登录到外部smtp服务器(如smtp.163.com) 二次转发,其实只要得到域名的邮件交换服务器地址(MX)就可以直接将邮件发出

    这里用到了dnsjava(下载地址:http://www.dnsjava.org/)来获取MX记录。考虑到效率问题可将每次获取的MX记录保存到xml或数据库,下次使用是先检索本地数据,若不存在再获取其MX记录。

SendMail.java

import org.xbill.DNS.*;
import java.util.Properties;
import javax.mail.internet.*;
import javax.mail.*;
import javax.mail.Address;
import javax.mail.Message;
import javax.activation.*;

public class SendMail
...{
    /** *//**
     * @param mailFrom 发送者,任意值
     * @param mailTo 接受者地址
     * @param subject 主题
     * @param content 内容
     * @param filepath 附件
     * @return 是否发送成功
     */
    public static boolean send(String mailFrom, String mailTo, String subject, String content,
                               String[] filepath)
    ...{
        if (!mailTo.matches("\w+([-_.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")) ...{ //判断格式
            return false;
        }
        try ...{
            String hostName = mailTo.split("@")[1];
            String host = null;

            Lookup lookup = new Lookup(hostName, Type.MX);  // 获取主机的MX记录
            lookup.run();
            if (lookup.getResult() != Lookup.SUCCESSFUL) ...{
                return false;
            }
            else ...{
                Record[] result = lookup.getAnswers();
                host = result[0].getAdditionalName().toString(); // 这里只取第一个服务器
            }

            Properties prop = new Properties();
            prop.put("mail.smtp.host", host);

            Session ssn = Session.getInstance(prop, null);
            //ssn.setDebug(true);
            //System.setOut(new PrintStream(new File("sendlog.log")));
            Address addressFrom = new InternetAddress(mailFrom, "Sender");
            Address addressTo = new InternetAddress(mailTo, "Receiver");
            
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            Multipart multipart = new MimeMultipart();

            messageBodyPart.setText(content);
            messageBodyPart.setHeader("content-type", "text/html");
            multipart.addBodyPart(messageBodyPart);
            DataSource source = null;

            if (filepath != null) ...{ //添加附件
                for (int i = 0; i < filepath.length; i++) ...{
                    messageBodyPart = new MimeBodyPart();
                    source = new FileDataSource(filepath[i]);
                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(filepath[i]);
                    multipart.addBodyPart(messageBodyPart);
                }
            }

            MimeMessage message = new MimeMessage(ssn);

            message.setSubject(subject);
            message.setFrom(addressFrom);
            message.addRecipient(Message.RecipientType.TO, addressTo);
            message.setContent(multipart);
            message.saveChanges();

            Transport tran = (Transport) ssn.getTransport("smtp");
            tran.connect();
            tran.sendMessage(message, message.getAllRecipients());
            tran.close();
            return true;
        } catch (Exception e) ...{
            //e.printStackTrace();
            return false;
        }
    }
}
测试:

public class Test 
...{
    public static void main(String[] args)
    ...{
        SendMail.send("MailFrom@YourDomain.Suffix", "MailTo@Domain.Suffix",  "你好",  "你好啊", null);
    }
}
注意:有些邮件服务器会验证当前提交邮件的链接的IP,即是验证YourDomain.Suffix对应的IP记录是否和当前链接相同,所以如果发送方地址随便填写可能发送不成功

JavaMail直接发送邮件

标签:

原文地址:http://www.cnblogs.com/jxldjsn/p/5537820.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!