java mail exchange 邮箱发送邮件

使用exchange 发送邮件是需要4个jar

jbex-examples.jar

jbex-javamail.jar

jbex-v1.4.8-basic.jar

javamail.jar

jar 资源 http://download.csdn.net/download/qweas123qwe/10119311


package com.moyosoft.exchange.javamail;


import java.io.*;
import java.util.*;

import javax.mail.*;
import javax.mail.event.*;
import javax.mail.internet.*;

import com.moyosoft.exchange.*;
import com.moyosoft.exchange.folder.*;
import com.moyosoft.exchange.item.*;
import com.moyosoft.exchange.mail.*;
import com.sun.mail.util.*;

public class JbexFolder extends Folder
{
    private ExchangeFolder folder;
    private boolean isOpen;
    
    protected JbexFolder(Store store, ExchangeFolder folder)
    {
        super(store);
        this.folder = folder;
    }

    public void appendMessages(Message[] msgs) throws MessagingException
    {
        for(Message msg : msgs)
        {
            appendMessage(msg);
        }
        
        notifyMessageAddedListeners(msgs);
    }

    public void appendMessage(Message msg) throws MessagingException
    {
        if(!(msg instanceof MimeMessage))
        {
            return;
        }

        MimeMessage mimeMessage = (MimeMessage) msg;
        ByteArrayOutputStream mimeBytesStream = new ByteArrayOutputStream();

        try
        {
            mimeMessage.writeTo(new CRLFOutputStream(mimeBytesStream));
        }
        catch(IOException e)
        {
            throw new MessagingException("Unable to write message content", e);
        }

        byte[] mimeContent = mimeBytesStream.toByteArray();

        if(mimeContent == null || mimeContent.length == 0)
        {
            return;
        }

        try
        {
            ExchangeMail mail = folder.createMail();
            mail.setMimeContent(mimeContent);
            mail.save();
        }
        catch(ExchangeServiceException e)
        {
            handleError(e);
        }
    }

    public void close(boolean expunge) throws MessagingException
    {
        isOpen = false;
        notifyConnectionListeners(ConnectionEvent.CLOSED);
    }

    public boolean create(int type) throws MessagingException
    {
        // TODO Folder creation
        return false;
    }

    public boolean delete(boolean recurse) throws MessagingException
    {
        try
        {
            folder.delete(true);
            return true;
        }
        catch(ExchangeServiceException e)
        {
            handleError(e);
        }
        
        return false;
    }

    public boolean exists() throws MessagingException
    {
        return folder != null;
    }

    public Message[] expunge() throws MessagingException
    {
        // TODO
        throw new UnsupportedOperationException("Deleting is not supported by this implementation");
    }

    public Folder getFolder(String name) throws MessagingException
    {
        if(exists())
        {
            try
            {
                return new JbexFolder(getStore(), folder.getFolders().get(name));
            }
            catch(ExchangeServiceException e)
            {
                handleError(e);
            }
        }
        
        return new JbexFolder(getStore(), null);
    }

    private void buildFullName(StringBuilder builder, ExchangeFolder folder) throws ExchangeServiceException, MessagingException
    {
        if(folder == null)
        {
            return;
        }
        
        buildFullName(builder, folder.getParentFolder());
        
        builder.append(folder.getDisplayName());
        builder.append(getSeparator());
    }

    public String getFullName()
    {
        try
        {
            if(exists())
            {
                StringBuilder builder = new StringBuilder();
                
                buildFullName(builder, folder.getParentFolder());
                builder.append(folder.getDisplayName());
                
                return builder.toString();
            }
        }
        catch(ExchangeServiceException e)
        {
        }
        catch(MessagingException e)
        {
        }
        
        return null;
    }

    private Message createMessage(ExchangeItem item) throws ExchangeServiceException, MessagingException
    {
        // TODO: Create a light-weight message first
        return
            new MimeMessage(
                ((JbexStore) store).getSession(),
                new ByteArrayInputStream(item.getMimeContentBytes()
            ));
    }
    
    public Message getMessage(int msgnum) throws MessagingException
    {
        if(exists())
        {
            try
            {
                return createMessage(folder.getItems().getAt(msgnum - 1));
            }
            catch(ExchangeServiceException e)
            {
                handleError(e);
            }
        }

        return null;
    }

    public int getMessageCount() throws MessagingException
    {
        try
        {
            return folder.getItemsCount();
        }
        catch(ExchangeServiceException e)
        {
            handleError(e);
        }
        
        return 0;
    }

    public String getName()
    {
        try
        {
            if(exists())
            {
                return folder.getDisplayName();
            }
        }
        catch(ExchangeServiceException e)
        {
        }
        catch(MessagingException e)
        {
        }
        
        return null;
    }

    public Folder getParent() throws MessagingException
    {
        if(exists())
        {
            try
            {
                return new JbexFolder(getStore(), folder.getParentFolder());
            }
            catch(ExchangeServiceException e)
            {
                handleError(e);
            }
        }
        
        return new JbexFolder(getStore(), null);
    }

    public Flags getPermanentFlags()
    {
        return null;
    }

    public char getSeparator() throws MessagingException
    {
        return '/';
    }

    public int getType() throws MessagingException
    {
        return HOLDS_FOLDERS | HOLDS_MESSAGES;
    }

    public boolean hasNewMessages() throws MessagingException
    {
        try
        {
            return folder.getUnreadItemsCount() > 0;
        }
        catch(ExchangeServiceException e)
        {
            handleError(e);
        }
        
        return false;
    }

    public boolean isOpen()
    {
        return isOpen;
    }

    public Folder[] list(String pattern) throws MessagingException
    {
        // TODO: Use the specified pattern
        
        try
        {
            ArrayList<Folder> folders = new ArrayList<Folder>();
            
            for(ExchangeFolder subfolder : folder.getFolders())
            {
                folders.add(new JbexFolder(getStore(), subfolder));
            }
            
            return folders.toArray(new Folder[folders.size()]);
        }
        catch(ExchangeServiceException e)
        {
            handleError(e);
        }
        
        return null;
    }

    public void open(int mode) throws MessagingException
    {
        isOpen = true;
        notifyConnectionListeners(ConnectionEvent.OPENED);
    }

    public boolean renameTo(Folder folder) throws MessagingException
    {
        try
        {
            this.folder.setDisplayName(folder.getName());
            this.folder.save();
            
            notifyFolderRenamedListeners(this);
            
            return true;
        }
        catch(ExchangeServiceException e)
        {
            handleError(e);
        }
        
        return false;
    }

    private void handleError(ExchangeServiceException e) throws MessagingException
    {
        throw new MessagingException(e.toString(), e);
    }

}

package com.moyosoft.exchange.javamail;

import java.net.*;

import javax.mail.*;

import com.moyosoft.exchange.*;

public class JbexStore extends Store
{
    private Exchange exchange;

    public JbexStore(Session session, URLName urlname)
    {
        super(session, urlname);
    }

    protected boolean protocolConnect(String host, int port, String user, String password) throws MessagingException
    {
        try
        {
            exchange = new Exchange(host, user, password);
        }
        catch(ExchangeServiceException e)
        {
            handleError(e);
        }

        return true;
    }

    public Folder getDefaultFolder() throws MessagingException
    {
        try
        {
            return new JbexFolder(this, exchange.getTopFolder());
        }
        catch(ExchangeServiceException e)
        {
            handleError(e);
        }
        
        return new JbexFolder(this, null);
    }

    public Folder getFolder(String name) throws MessagingException
    {
        try
        {
            if("INBOX".equals(name))
            {
                return new JbexFolder(this, exchange.getInboxFolder());
            }
            else
            {
                return new JbexFolder(this, exchange.getTopFolder(name));
            }
        }
        catch(ExchangeServiceException e)
        {
            handleError(e);
        }
        
        return new JbexFolder(this, null);
    }

    public Folder getFolder(URLName urlName) throws MessagingException
    {
        try
        {
            return getFolder(urlName.getURL().getPath());
        }
        catch(MalformedURLException ex)
        {
            throw new MessagingException(ex.getMessage(), ex);
        }
    }

    private void handleError(ExchangeServiceException e) throws MessagingException
    {
        throw new MessagingException(e.toString(), e);
    }
    
    public Session getSession()
    {
        return session;
    }
}
package com.moyosoft.exchange.javamail;

import java.io.*;

import javax.mail.*;
import javax.mail.internet.*;

import com.moyosoft.exchange.*;
import com.moyosoft.exchange.mail.*;
import com.sun.mail.util.*;

public class JbexTransport extends Transport
{
    private Exchange exchange;

    public JbexTransport(Session session, URLName urlname)
    {
        super(session, urlname);
    }

    protected boolean protocolConnect(String host, int port, String user, String password) throws MessagingException
    {
        try
        {
            exchange = new Exchange(host, user, password);
        }
        catch(ExchangeServiceException e)
        {
            handleError(e);
        }

        return true;
    }

    public void sendMessage(Message msg, Address[] addresses) throws MessagingException
    {
        try
        {
            ExchangeMail mail = createMail(msg, addresses);

            if(mail == null)
            {
                throw new MessagingException("Unable to create the message");
            }

            mail.send();
        }
        catch(ExchangeServiceException e)
        {
            handleError(e);
        }
    }

    private ExchangeMail createMail(Message msg, Address[] addresses) throws ExchangeServiceException, MessagingException
    {
        if(!(msg instanceof MimeMessage))
        {
            return null;
        }

        MimeMessage mimeMessage = (MimeMessage) msg;
        ByteArrayOutputStream mimeBytesStream = new ByteArrayOutputStream();

        try
        {
            mimeMessage.writeTo(new CRLFOutputStream(mimeBytesStream));
        }
        catch(IOException e)
        {
            throw new MessagingException("Unable to write message content", e);
        }

        byte[] mimeContent = mimeBytesStream.toByteArray();

        if(mimeContent == null || mimeContent.length == 0)
        {
            return null;
        }

        ExchangeMail mail = exchange.createMail();
        mail.setMimeContent(mimeContent);

        return mail;
    }

    private void handleError(ExchangeServiceException e) throws MessagingException
    {
        throw new MessagingException(e.toString(), e);
    }
}
package com.moyosoft.exchange.javamail;

import java.util.Properties;   
public class MailSenderInfo {   
    // 发送邮件的服务器的IP和端口   
    private String mailServerHost;   
    private String mailServerPort = "25";   
    // 邮件发送者的地址   
    private String fromAddress;   
    // 邮件接收者的地址   
    private String toAddress;   
    // 登陆邮件发送服务器的用户名和密码   
    private String userName;   
    private String password;   
    // 是否需要身份验证   
    private boolean validate = false;   
    // 邮件主题   
    private String subject;   
    // 邮件的文本内容   
    private String contents;   
    // 邮件附件的文件名   
    private String[] attachFileNames;     
    /**  
      * 获得邮件会话属性  
      */   
    public Properties getProperties(){   
      Properties p = new Properties();   
      p.put("mail.smtp.host", this.mailServerHost);   
      p.put("mail.smtp.port", this.mailServerPort);   
      p.put("mail.smtp.auth", validate ? "true" : "false");   
      return p;   
    }   
    public String getMailServerHost() {   
      return mailServerHost;   
    }   
    public void setMailServerHost(String mailServerHost) {   
      this.mailServerHost = mailServerHost;   
    }  
    public String getMailServerPort() {   
      return mailServerPort;   
    }  
    public void setMailServerPort(String mailServerPort) {   
      this.mailServerPort = mailServerPort;   
    }  
    public boolean isValidate() {   
      return validate;   
    }  
    public void setValidate(boolean validate) {   
      this.validate = validate;   
    }  
    public String[] getAttachFileNames() {   
      return attachFileNames;   
    }  
    public void setAttachFileNames(String[] fileNames) {   
      this.attachFileNames = fileNames;   
    }  
    public String getFromAddress() {   
      return fromAddress;   
    }   
    public void setFromAddress(String fromAddress) {   
      this.fromAddress = fromAddress;   
    }  
    public String getPassword() {   
      return password;   
    }  
    public void setPassword(String password) {   
      this.password = password;   
    }  
    public String getToAddress() {   
      return toAddress;   
    }   
    public void setToAddress(String toAddress) {   
      this.toAddress = toAddress;   
    }   
    public String getUserName() {   
      return userName;   
    }  
    public void setUserName(String userName) {   
      this.userName = userName;   
    }  
    public String getSubject() {   
      return subject;   
    }  
    public void setSubject(String subject) {   
      this.subject = subject;   
    }  
    public String getContents() {   
      return contents;   
    }  
    public void setContents(String textContent) {   
      this.contents = textContent;   
    }   
}  
package com.moyosoft.exchange.javamail;

import javax.mail.*;  

public class MyAuthenticator extends Authenticator{  
    String userName=null;  
    String password=null;  
       
    public MyAuthenticator(){  
    }  
    public MyAuthenticator(String username, String password) {   
        this.userName = username;   
        this.password = password;   
    }   
    protected PasswordAuthentication getPasswordAuthentication(){  
        return new PasswordAuthentication(userName, password);  
    }  

package com.moyosoft.exchange.javamail;

import java.io.ObjectInputStream.GetField;
import java.util.*;

import javax.mail.*;
import javax.mail.internet.*;


public class TestJbexJavaMailProvider
{
    public static void main(String[] argv) throws NoSuchProviderException, MessagingException
    {
        // Set here the Exchange server's hostname and login username/password:
        MailSenderInfo mailInfo = new MailSenderInfo();   
    
          mailInfo.setMailServerHost("mail.pjoe.com.cn");   
          mailInfo.setMailServerPort("25");   
          mailInfo.setValidate(false);   
          mailInfo.setUserName("******");   
          mailInfo.setPassword("*****");//您的邮箱密码   
          mailInfo.setFromAddress("******");   
          mailInfo.setToAddress("******");   
          mailInfo.setSubject("邮件测试");   
          mailInfo.setContents("邮件内容");
        sendMessage(mailInfo);
        
    }

    private static void sendMessage(MailSenderInfo mail ) throws NoSuchProviderException, MessagingException
    {
         Properties pro = mail.getProperties();  
        // Create a session
        
        MyAuthenticator authenticator = null;   
         if (mail.isValidate()) {   
              // 如果需要身份认证,则创建一个密码验证器   
                authenticator = new MyAuthenticator(mail.getUserName(), mail.getPassword());   
          }  
         Session session = Session.getDefaultInstance(pro,authenticator);
        // Create and connect to the transport
        Transport transport = session.getTransport("jbexTransport");
        System.out.println("是否可以连接上邮箱?");
        try {
            transport.connect(mail.getMailServerHost(),  mail.getUserName(), mail.getPassword());
            System.out.println("邮箱连接没有问题");
        } catch (Exception e) {
            System.out.println("邮箱连接有问题");
            e.printStackTrace();
}
        // Recipients
        Address[] recipients = new Address[] {new InternetAddress(mail.getToAddress())};
        
        // Create a message
        Message msg = new MimeMessage(session);
        msg.setRecipients(Message.RecipientType.TO, recipients);
        msg.setSubject(mail.getSubject());
          // 设置邮件消息的主要内容   
        String mailContent = mail.getContents();   
        msg.setContent(mailContent,"text/plain");  
        msg.saveChanges();
        
        // Send the message
        transport.sendMessage(msg, recipients);
        System.out.println("成功");
        // Disconnect
        transport.close();
    }    

}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,以下是一个简单的 Java 发送 Exchange 邮箱邮件的示例代码: ```java import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; public class ExchangeMailSender { public static void main(String[] args) { final String username = "your_username"; final String password = "your_password"; final String recipientEmail = "recipient_email_address"; final String subject = "Test Email"; final String body = "This is a test email sent from Java."; Properties props = new Properties(); props.put("mail.smtp.host", "your_exchange_server"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.port", "587"); // Change to the appropriate port number Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(username)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail)); message.setSubject(subject); message.setText(body); Transport.send(message); System.out.println("Email sent successfully."); } catch (MessagingException e) { System.out.println("Failed to send email. Error message: " + e.getMessage()); } } } ``` 请将代码中的以下信息替换为您自己的信息: - `your_username`:您的 Exchange 邮箱用户名 - `your_password`:您的 Exchange 邮箱密码 - `recipient_email_address`:收件人的邮箱地址 - `your_exchange_server`:您的 Exchange 邮箱服务器域名或 IP 地址 请注意,此代码需要 JavaMail API 和 Exchange Web Services Java API。您需要将这些 API 添加到您的项目中才能运行此代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值