HtmlEmail email = new HtmlEmail(); 
email.setHostName("192.168.1.123");//服务器   
email.setSmtpPort(25);  
email.addTo("[email protected]");//设置接收方 
email.setFrom("[email protected]");//设置发送方
email.getMailSession().getProperties().put("mail.smtp.auth", "false");             
email.setCharset("UTF-8");//设置编码                             
email.setSubject("你好");
email.setHtmlMsg("<html><body>hello</body></html>");
email.setPopBeforeSmtp(true,"test.cn","bcrcw","123456");
if(!email.send().isEmpty()){
System.out.println("success");
}else{
System.out.println("error");
}
无验证发送,本地搭建的邮件服务器,发送没有错误,控制台输出:success
但是有些里没有收到邮件
高手你在哪里!我需要你。
小女子无分,友情帮助吧!在此谢过

解决方案 »

  1.   

    谢过各位,接受方没有问题,我这么写,如果用smtp.163.com服务器就不会有问题正常发送(不过需要验证用户名和密码),我用本地搭建的就不行,望各位帮忙
      

  2.   

    补充:HtmlEmail email = new HtmlEmail(); 
    email.setHostName("test.cn");//服务器   
    email.setSmtpPort(25);
    email.setAuthentication("bcrcw","123456");//验证用户  
    email.addTo("[email protected]");//设置接收方 
    email.setFrom("[email protected]");//设置发送方
    email.getMailSession().getProperties().put("mail.smtp.auth", "true");
    email.setCharset("UTF-8");//设置编码                             
    email.setSubject("你好");
    email.setHtmlMsg("<html><body>hello</body></html>");
    if(!email.send().isEmpty()){
    System.out.println("success");
    }else{
    System.out.println("error");
    }
    我用上边的例子发送,用邮件服务器smtp.163.com发送就能成功。
    用自己架设的服务器发送,用命令发送邮件成功了,但是用程序发送就报如下错误javax.mail.SendFailedException: Invalid Addresses;
      nested exception is:
    com.sun.mail.smtp.SMTPAddressFailedException: 554 <[email protected]>: Relay access denied at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1196)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:584)
    at javax.mail.Transport.send0(Transport.java:169)
    at javax.mail.Transport.send(Transport.java:98)
    at action.SendEmailAction.execute(SendEmailAction.java:81)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488)
    at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:619)
    Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 554 <[email protected]>: Relay access denied at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1094)
    ... 69 more
      

  3.   

    首先,你不明白什么是邮件服务器,什么客户端
    jmail只作为一个客户端存在,提交一份邮件的流程:
    包装邮件信息 -> 提交给邮件服务器 -> 邮件服务器检索收件人地址 -> 发送邮件 -> 接收方处理邮件 -> ...你只进行到第二步,提交邮件,当然,本地邮件服务器只要开着,你提交邮件的动作当然完成了,这有问题吗?
    你应该做的是去翻邮件服务器的日志记录,没有收到只说明你的邮件服务器不能外发邮件,或者外发有错误
    你得确定你的邮件服务器可以正常收发外部邮件另外,这里没有高手,做IT的别这么浮躁
      

  4.   

    正常 163有很严格的邮件检查机制
    email.setFrom("[email protected]");//设置发送方
    163对收发方都进行relay反查,这种地址肯定给当成junk给ban掉
      

  5.   

    就这代码
    看不出来正确与否
    www.bsniss.com
    这个也是用java做的
    是没有问题的
      

  6.   

    我现在就是用程序发送得话,内网可以发,发外服务的就不行了,报错
    javax.mail.SendFailedException: Invalid Addresses;
      nested exception is:
    com.sun.mail.smtp.SMTPAddressFailedException: 554 <[email protected]>: Relay access denied at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1196)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:584)
      

  7.   

    javax.mail.SendFailedException: Invalid Addresses;发送失败,错误信息是无效的地址,你看看你哪个地址有问题吧。人家提示都在这呢
      

  8.   

    [email protected] 有这个邮箱么?
      

  9.   

    地址是对的啊!我用smtp.163.com 都能发的。我都快疯了
      

  10.   

    哎 怎么就和你说不清楚...
    [email protected] <- 这个地址你觉得有效?
    163会认识你这么个地址?比如说你家里小名叫二蛋,然后跑快递公司说 二蛋寄个快递,钱找二蛋收,快递公司理你不?
      

  11.   

    那怎么在dos命令里就能发送呢
      

  12.   

    你架设的邮局是不是支持POP和SMTP协议?
      

  13.   

    看下我的错误日志
    DEBUG: setDebug: JavaMail version 1.4ea
    DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
    DEBUG SMTP: useEhlo true, useAuth true
    DEBUG SMTP: trying to connect to host "test.cn", port 25, isSSL false
    220 test.cn ESMTP Postfix
    DEBUG SMTP: connected to host "test.cn", port: 25EHLO cn-07
    250-test.cn
    250-PIPELINING
    250-SIZE 10240000
    250-VRFY
    250-ETRN
    250-AUTH PLAIN NTLM DIGEST-MD5 GSSAPI CRAM-MD5 LOGIN
    250 8BITMIME
    DEBUG SMTP: Found extension "PIPELINING", arg ""
    DEBUG SMTP: Found extension "SIZE", arg "10240000"
    DEBUG SMTP: Found extension "VRFY", arg ""
    DEBUG SMTP: Found extension "ETRN", arg ""
    DEBUG SMTP: Found extension "AUTH", arg "PLAIN NTLM DIGEST-MD5 GSSAPI CRAM-MD5 LOGIN"
    DEBUG SMTP: Found extension "8BITMIME", arg ""
    DEBUG SMTP: Attempt to authenticate
    AUTH LOGIN
    334 VXNlcm5hbWU6
    YmNyY3c=
    334 UGFzc3dvcmQ6
    MTIzNDU2
    235 Authentication successful
    DEBUG SMTP: use8bit false
    MAIL FROM:<[email protected]>
    250 Ok
    RCPT TO:<[email protected]>
    554 <[email protected]>: Relay access denied
    DEBUG SMTP: Invalid Addresses
    DEBUG SMTP:   [email protected]
    DEBUG SMTP: Sending failed because of invalid destination addresses
    RSET
    250 Ok
    javax.mail.SendFailedException: Invalid Addresses;
      nested exception is:
    com.sun.mail.smtp.SMTPAddressFailedException: 554 <[email protected]>: Relay access denied at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1196)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:584)
      

  14.   

    之前一直在做本地邮件服务器发送,可是没有成功,都说什么反解析失败什么的原因,具体的也不太清楚,最近又学习了用java做邮件发送服务器,还真的成功了分享给大家(以下发送只包括文字内容,不包括附加及图片,如有不明白的可以联系我)java运行:main运行测试的话,包需要java2E 1.4
    javaweb运行:包需要javaEE 5
    运行调用SendMailGUI中方法run("发送方地址(随便起名,但要符合邮件样式@.)", "接收方地址", "发送主题", "发送内容") 
    类:SendMailGUI
    package action;
    import java.util.Arrays;
    import java.util.Hashtable;
    import javax.naming.Context;
    import javax.naming.directory.DirContext;
    import javax.naming.directory.InitialDirContext;
    import javax.naming.directory.Attributes;
    import javax.naming.NamingEnumeration;
    import javax.naming.directory.Attribute;
    import java.io.ByteArrayOutputStream;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.Properties;
    import javax.mail.Session;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.InternetAddress;
    import javax.mail.Message;
    import javax.mail.internet.MimeMultipart;
    import javax.mail.BodyPart;
    import javax.mail.internet.MimeBodyPart;
    import javax.activation.FileDataSource;
    import javax.activation.DataHandler;
    import javax.mail.internet.MimeUtility;
    import javax.mail.Multipart;
    import java.util.Date;
    import javax.mail.Transport;public class SendMailGUI{
     /** serialVersionUID */
    String imagePath = null;
    javax.swing.JProgressBar bar = new javax.swing.JProgressBar();
    public int run(String from, String to, String title, String content) {       
            MailMessage mesg = new MailMessage(from,to,title,content);
            try
            {
                sendMail(mesg);         
                return 1;
            }catch (Exception ex){
                return 0;
            }
        }
    private void sendMail(MailMessage mesg) throws Exception
    {
        //DNS服务器
       String dns = "dns://";
       //得到接受方的服务器域名
       String domain = mesg.getTo().substring(mesg.getTo().indexOf('@') + 1);
       Hashtable env = new Hashtable();
       env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
       env.put(Context.PROVIDER_URL, dns);
       DirContext ctx = new InitialDirContext(env);
       Attributes attrs = ctx.getAttributes(domain, new String[] {"MX"});
       if (attrs == null || attrs.size() <= 0) {
           throw new java.lang.IllegalStateException("错误:你的DNS服务器没有相应的MX记录!");
       }
       NamingEnumeration servers = attrs.getAll();
       // 列出所有邮件服务器:
       String smtpHost = null;
       boolean isSend = false;
       StringBuffer buf = new StringBuffer();
       while (servers.hasMore())
       {
           Attribute hosts = (Attribute) servers.next();
           for (int i = 0; i < hosts.size(); ++i)
           {
               smtpHost = (String) hosts.get(i);
               smtpHost = smtpHost.substring(smtpHost.lastIndexOf(' ') + 1);
               try{
                   sendEms(smtpHost, mesg);
                   isSend = true;
                   return;
               }catch(Exception e){
                   e.printStackTrace();
                   buf.append(e.toString()).append("\r\n");
                   continue;
               }
           }
       }
       if (!isSend) {
           throw new java.lang.IllegalStateException("错误:发送失败," + buf.toString());
       }
    }private void sendEms(String smtpHost, MailMessage mesg) throws Exception{
        Properties p = System.getProperties();
        p.put("mail.smtp.host", smtpHost);
        p.put("mail.smtp.port", "25");
        p.put("mail.smtp.auth", "false");
        Session session = Session.getInstance(p, null);
        //session.setDebug(true);
        Message  mimeMessage = new MimeMessage (session);
        mimeMessage.setFrom(new InternetAddress(mesg.getFrom()));//可发匿名信
        mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mesg.getTo()));
        mimeMessage.setSubject(mesg.getTitle());
        mimeMessage.setHeader("X-Mailer", "JavaMail");
        mimeMessage.setSentDate(new Date());        
        MimeMultipart  mimeMultipart = new MimeMultipart();
        //内容部分.
        BodyPart contentBodyPart = new MimeBodyPart();
        contentBodyPart.setContent(mesg.getContent(), "text/html;charset=GB2312");
        mimeMultipart.addBodyPart(contentBodyPart);
         // add the attachments  
        mimeMessage.setContent(mimeMultipart);
        mimeMessage.saveChanges();
        //发送
        Transport.send(mimeMessage);
    }
    public  byte[] readFile(String file){ 
    FileInputStream fis = null; 
    ByteArrayOutputStream bos = null; 
    try { 
    fis = new FileInputStream(file); 
    bos = new ByteArrayOutputStream(); 
    int bytesRead; 
    byte buffer[] = new byte[1024 * 1024]; 
    while ((bytesRead = fis.read(buffer)) != -1) { 
    bos.write(buffer, 0, bytesRead); 
    Arrays.fill(buffer, (byte) 0); 

    }catch (IOException e1) { 
    e1.printStackTrace(); 
    } finally { 
    try { 
    if (bos != null) 
    bos.close(); 
    }catch (IOException e) { 
    e.printStackTrace(); 


    return bos.toByteArray(); 


    class MailMessage
    {
        private String from = null;
        private String to   = null;
        private String title   = null;
        private String content = null;
        public MailMessage (String from, String to, String title, String content)
        {
            this.from = from;
            this.to = to;
            this.title = title;
            this.content = content;
        }
        public String getFrom()
        {
            return this.from;
        }
        public String getTo()
        {
            return this.to;
        }
        public String getTitle()
        {
            return this.title;
        }
        public String getContent()
        {
            return this.content;
        }
    }//--------------------------类:ByteArrayDataSource 
    package action;
    import java.io.*;
    import javax.activation.*;public class ByteArrayDataSource implements DataSource{
    /*** Data to write. */
    private byte[] _data;
    /*** Content-Type. */
    private String _type;  /* Create a datasource from an input stream */
    public ByteArrayDataSource(InputStream is,String type)
    {
    _type = type;
    try
    {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    int ch;  http://www.mscto.com // XXX : must be made more efficient by
    // doing buffered reads, rather than one byte reads
    while ((ch = is.read()) != -1)
    os.write(ch);
    _data = os.toByteArray();
    }
    catch (IOException ioe)
    {
    }
    }
    /* Create a datasource from a byte array */ public ByteArrayDataSource(byte[] data,String type)
    {
    _data = data;
    _type = type;
    }
    /* Create a datasource from a String */
    public ByteArrayDataSource(String data,String type)
    {
    try
    {
    // Assumption that the string contains only ascii
    // characters ! Else just pass in a charset into this
    // constructor and use it in getBytes()
    _data = data.getBytes("iso-8859-1");
    }
    catch (UnsupportedEncodingException uee)
    {
    }
    _type = type;
    }
    public InputStream getInputStream()
    throws IOException
    {
    if (_data == null)
    throw new IOException("no data");
    return new ByteArrayInputStream(_data);
    }
    public OutputStream getOutputStream() 
    throws IOException
    {
    throw new IOException("cannot do this");
    }
    public String getContentType()
    {
    return _type;
    }
    public String getName()
    {
    return "dummy";
    }
    }