开发者社区> 问答> 正文

发送邮件失败邮箱服务器是exchange2010?报错

@红薯:http://www.oschina.net/code/snippet_12_160,我使用这里的方法 发送邮件失败。
邮箱服务器安装的是:exchange2010

我使用jbex-javamail.jar,jbex-v1.4.6-eval.jar,jcifs-1.3.15.jar,加上mail.jar.可以发送简单邮件,代码如下:

public static void main(String[] argv) throws NoSuchProviderException, MessagingException
	{
		// Set here the Exchange server's hostname and login username/password:
		String hostname = "host";
		String username = "账号";
		String password = "密码";
		
		sendMessage(hostname, username, password);
	}

private static void sendMessage(String hostname, String username, String password) throws NoSuchProviderException, MessagingException  {   // Create a session   Session session = Session.getDefaultInstance(new Properties());

  // Create and connect to the transport   Transport transport = session.getTransport("jbexTransport");   transport.connect(hostname, username, password);

  // Recipients   Address[] recipients = new Address[] {new InternetAddress("zlczhou@yeah.net")};      // Create a message   Message msg = new MimeMessage(session);   msg.setRecipients(Message.RecipientType.TO, recipients);   msg.setSubject("Test message");   msg.setContent("Hello from JavaMail by jbex.jar", "text/plain");   msg.saveChanges();      // Send the message   transport.sendMessage(msg, recipients);

  // Disconnect   transport.close();  } 

但是 使用上边的方法 改写您原来写的MailSender.java如下:
/**===========================================
 *        Copyright (C) 2012 Tempus
 *           All rights reserved
 *
 *  项 目 名: myjmail
 *  文 件 名: MailSender.java
 *  版本信息: V1.0.0 
 *  作    者: admin
 *  日    期: 2012-8-29-上午09:19:13
 * 
 ============================================*/

package com.tempus.common.utils;

/**
 * 类 名 称: MailSender
 * 类 描 述: 
 * 创 建 人: admin
 * 创建时间: 2012-8-29 上午09:19:13
 *
 * 修 改 人: admin
 * 操作时间: 2012-8-29 上午09:19:13
 * 操作原因: 
 * 
 */
/**
 * 邮件发送组件类
 * 该类需要三个jar文件: mail.jar,activation.jar,htmlparser.jar
 * @version 1.0
 */
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.SendFailedException;
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 org.apache.log4j.Logger;


import sun.misc.BASE64Encoder;
/**
 * 邮件发送组件,具体的使用方法参照该类的main方法
 * @author Winter Lau
 */
public abstract class MailSender extends Authenticator{
	
	private static Logger logger = Logger.getLogger(MailSender.class);
    private String username = null;		//邮件发送帐号用户名
    private String userpasswd = null;	//邮件发送帐号用户口令
    protected BodyPart messageBodyPart = null;
    protected Multipart multipart = new MimeMultipart("related");
    protected Message mailMessage = null;
    protected Session mailSession = null;
    protected Properties mailProperties = System.getProperties();
    protected Transport transport = null;
    protected InternetAddress mailFromAddress = null;
    protected Address[] mailToAddressTo = null;
    protected Address[] mailToAddressCc = null;
    protected Address[] mailToAddressBcc = null;
    protected Authenticator authenticator = null;
    protected String mailSubject = "";
    protected Date mailSendDate = null;
//    protected ExchangeMail mail = null;

    protected MailSender(){}
    /**
     * 构造函数
     * @param smtpHost
     * @param username
     * @param password
     */
    protected MailSender(String smtpHost, String username, String password) {
        this.username = username;
        this.userpasswd = password;
        final String uname = username;
        final String upass = password;
        mailProperties.put("mail.smtp.host", smtpHost);
        mailProperties.put("mail.smtp.auth", "true"); //设置smtp认证,很关键的一句
        mailProperties.put("mail.smtp.port", "25");
        mailSession = Session.getDefaultInstance(mailProperties,new Authenticator()
		{
        	protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(uname, upass);
            }
		});
        try
		{
			this.transport = mailSession.getTransport("jbexTransport");
		} catch (NoSuchProviderException e)
		{
			e.printStackTrace();
		}
        mailMessage = new MimeMessage(mailSession);
        messageBodyPart = new MimeBodyPart();
    }
    /**
     * 构造一个纯文本邮件发送实例
     * @param smtpHost
     * @param username
     * @param password
     * @return
     */
    public static MailSender getTextMailSender(String smtpHost, String username, String password) {        
        return new MailSender(smtpHost,username,password) {
            public void setMailContent(String mailContent) throws MessagingException {
                messageBodyPart.setText(mailContent);
                multipart.addBodyPart(messageBodyPart);
            }            
        };        
    }
    /**
     * 用于实现邮件发送用户验证
     * @see javax.mail.Authenticator#getPasswordAuthentication
     */
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, userpasswd);
    }
    
    /**
     * 设置邮件标题
     * @param mailSubject
     * @throws MessagingException
     */
    public void setSubject(String mailSubject) throws MessagingException {
        this.mailSubject = mailSubject;
        mailMessage.setSubject(mailSubject);
    }

    /**
     * 所有子类都需要实现的抽象方法,为了支持不同的邮件类型
     * @param mailContent
     * @throws MessagingException
     */
    protected abstract void setMailContent(String mailContent) throws MessagingException;

    /**
     * 设置邮件发送日期
     * @param sendDate
     * @throws MessagingException
     */
    public void setSendDate(Date sendDate) throws MessagingException {
        this.mailSendDate = sendDate;
        mailMessage.setSentDate(sendDate);
    }
    /**
     * 设置发件人地址
     * @param mailFrom
     * @throws MessagingException
     */
    public void setMailFrom(String mailFrom) throws MessagingException {
        mailFromAddress = new InternetAddress(mailFrom);
        mailMessage.setFrom(mailFromAddress);
    }

//    /**
//     * 设置收件人地址,收件人类型为to,cc,bcc(大小写不限)
//     * @param mailTo   邮件接收者地址
//     * @param mailType 值为to,cc,bcc
//     * @author Liudong
//     */
//    public void setMailTo(String[] mailTo, String mailType) throws Exception {
//        for (int i = 0; i < mailTo.length; i++) {
//            mailToAddress = new InternetAddress(mailTo[i]);
//            if (mailType.equalsIgnoreCase("to")) {
//                mailMessage.addRecipient(Message.RecipientType.TO,mailToAddress);
//            } else if (mailType.equalsIgnoreCase("cc")) {
//                mailMessage.addRecipient(Message.RecipientType.CC,mailToAddress);
//            } else if (mailType.equalsIgnoreCase("bcc")) {
//                mailMessage.addRecipient(Message.RecipientType.BCC,mailToAddress);
//            } else {
//                throw new Exception("Unknown mailType: " + mailType + "!");
//            }
//        }
//    }
    /**
     * 设置邮件发送附件
     * @param attachmentName
     * @throws MessagingException
     * @throws UnsupportedEncodingException 
     */
    public void setAttachments(String attachmentName) throws MessagingException, UnsupportedEncodingException {
    	DataSource source = null;
    	try
		{
    		source = new FileDataSource(attachmentName);
			
		} catch (Exception e)
		{
			logger.error("没有找到"+attachmentName+e.getMessage());
		}
        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(source));        
        String encoding = System.getProperty("sun.jnu.encoding");//获取系统的默认编码方式
        BASE64Encoder enc = new BASE64Encoder();//该类位于jre/lib/rt.jar中 
        messageBodyPart.setFileName("=?"+encoding+"?B?"+enc.encode((source.getName()).getBytes())+"?=");
        multipart.addBodyPart(messageBodyPart);
    }
//    /**
//     * 开始发送邮件
//     * @throws MessagingException
//     * @throws SendFailedException
//     */
//    public void sendMail() throws MessagingException, SendFailedException {
//        if (mailToAddress == null)
//            throw new MessagingException("请你必须你填写收件人地址!");
//        mailMessage.setContent(multipart);
//        Transport.send(mailMessage);
//    }
    /**
     * 设置收件人地址,收件人类型为to,cc,bcc(大小写不限)
     * @param mailTo   邮件接收者地址
     * @param mailType 值为to,cc,bcc
     * @author Liudong
     */
    public void setMailTo(String[] mailTo, String mailType) throws Exception {
		if (mailType.equalsIgnoreCase("to")) {
    	    mailToAddressTo = new Address[mailTo.length];
    	    for (int i = 0; i < mailTo.length; i++) {
    	  	  mailToAddressTo[i] = new InternetAddress(mailTo[i]);
    	    }
    	    mailMessage.setRecipients(Message.RecipientType.TO,mailToAddressTo);
		} else if (mailType.equalsIgnoreCase("cc")) {
			mailToAddressCc = new Address[mailTo.length];
			for (int i = 0; i < mailTo.length; i++)
			{
				mailToAddressCc[i] = new InternetAddress(mailTo[i]);
			}
			mailMessage.setRecipients(Message.RecipientType.CC,mailToAddressCc);
		} else if (mailType.equalsIgnoreCase("bcc")) {
			mailToAddressBcc = new Address[mailTo.length];
			for (int i = 0; i < mailTo.length; i++)
			{
				mailToAddressBcc[i] = new InternetAddress(mailTo[i]);
			}
			mailMessage.setRecipients(Message.RecipientType.BCC,mailToAddressBcc);
		} else {
		    throw new Exception("Unknown mailType: " + mailType + "!");
		}
    }
    /**
     * 开始发送邮件
     * @throws MessagingException
     * @throws SendFailedException
     * @throws ExchangeServiceException 
     */
    @SuppressWarnings("static-access")
	public void sendMail() throws MessagingException{
        if (mailToAddressTo == null)
            throw new MessagingException("请你你填写收件人地址!");
        mailMessage.setContent(multipart);
//		Transport.send(mailMessage);
        transport.connect(mailProperties.getProperty("mail.smtp.host"), username, userpasswd);
        transport.send(mailMessage, mailToAddressTo);
        transport.close();
    }
}

报错:用于提交此请求的用户帐户无权代表指定的发送帐户发送邮件。

可是查看了下 账号的最大权限都开了。为什么还提示错误呢?

MailUtis.java

public class MailUtils extends MailSender
{

	/**
	 * 新的实例: MailUtils.
	 *
	 */
	public MailUtils(){}
	public MailUtils(String smtpHost,String username,String password){
		super(smtpHost, username, password);
	}
	/**
	 * 发送邮件
	 */
	@Override
	public void setMailContent(String mailContent) throws MessagingException
	{
		messageBodyPart.setText(mailContent);
        multipart.addBodyPart(messageBodyPart);
	}

}

调用方式:

MailUtils sendmail = new MailUtils(mailHost, mailUser, mailPassword);

请问是什么原因呢?

展开
收起
爱吃鱼的程序员 2020-06-22 22:39:40 818 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    publicstaticvoidmain(String[]argv)throwsNoSuchProviderException,MessagingException
    {
    //SetheretheExchangeserver'shostnameandloginusername/password:
    Stringhostname="host";
    Stringusername="账号";
    Stringpassword="密码";

    sendMessage(hostname,username,password);
    }


    privatestaticvoidsendMessage(Stringhostname,Stringusername,Stringpassword)throwsNoSuchProviderException,MessagingException
     {
      //Createasession
      Sessionsession=Session.getDefaultInstance(newProperties());
      //Createandconnecttothetransport
      Transporttransport=session.getTransport("jbexTransport");
      transport.connect(hostname,username,password);
      //Recipients
      Address[]recipients=newAddress[]{newInternetAddress(zlczhou@yeah.net)};  
      //Createamessage
      Messagemsg=newMimeMessage(session);
      msg.setRecipients(Message.RecipientType.TO,recipients);
      msg.setSubject("Testmessage");
      msg.setContent("HellofromJavaMailbyjbex.jar","text/plain");
      msg.saveChanges();  
      //Sendthemessage
      transport.sendMessage(msg,recipients);
      //Disconnect
      transport.close();
     }

     

    这种方式发送没问题了,具体什么原因,以后有时间在看看

    <spanstyle="background-color:#b7e8bd;">没有人吗?

    <aclass='referer'target='_blank'>@红薯一下,你就知道将原来红薯的代码改为第一个示例的那样,就可以发送邮件了。但是还是不太清楚,当邮件服务器为exchange2010后为什么红薯那个发邮件的代码就不行了呢!!!??

    -.-报什么错//


    <divclass="ref">

    引用来自“杜宏浩”的答案

    <divclass=ref_body>

    -.-报什么错//


    你的类中怎么出现这个了"zlczhou@yeah.net".
    <divclass="ref">

    引用来自“杜宏浩”的答案

    <divclass=ref_body>你的类中怎么出现这个了"zlczhou@yeah.net".

    Exceptioninthread"main"javax.mail.MessagingException:com.moyosoft.exchange.ExchangeServiceException:HTTPerror:404-NotFound;

      什么情况啊?亲

    <divclass="ref">

    引用来自“javacc”的答案

    <divclass=ref_body>publicstaticvoidmain(String[]argv)throwsNoSuchProviderException,MessagingException
    {
    //SetheretheExchangeserver'shostnameandloginusername/password:
    Stringhostname="host";
    Stringusername="账号";
    Stringpassword="密码";

    sendMessage(hostname,username,password);
    }


    privatestaticvoidsendMessage(Stringhostname,Stringusername,Stringpassword)throwsNoSuchProviderException,MessagingException
     {
      //Createasession
      Sessionsession=Session.getDefaultInstance(newProperties());
      //Createandconnecttothetransport
      Transporttransport=session.getTransport("jbexTransport");
      transport.connect(hostname,username,password);
      //Recipients
      Address[]recipients=newAddress[]{newInternetAddress(zlczhou@yeah.net)};  
      //Createamessage
      Messagemsg=newMimeMessage(session);
      msg.setRecipients(Message.RecipientType.TO,recipients);
      msg.setSubject("Testmessage");
      msg.setContent("HellofromJavaMailbyjbex.jar","text/plain");
      msg.saveChanges();  
      //Sendthemessage
      transport.sendMessage(msg,recipients);
      //Disconnect
      transport.close();
     }

     

    这种方式发送没问题了,具体什么原因,以后有时间在看看

    2020-06-22 22:39:57
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
如何运维千台以上游戏云服务器 立即下载
网站/服务器取证 实践与挑战 立即下载
ECS块储存产品全面解析 立即下载