exchange服务器之java mail exchange 邮箱发送邮件
白羽 2018-12-04 来源 :网络 阅读 884 评论 0

摘要:本文将带你了解exchange服务器之java mail exchange 邮箱发送邮件,希望本文对大家学Exchange有所帮助。

    本文将带你了解exchange服务器之java mail exchange 邮箱发送邮件,希望本文对大家学Exchange有所帮助。


<

使用exchange 发送邮件是需要4个jar 
jbex-examples.jar
jbex-javamail.jar
jbex-v1.4.8-basic.jar
javamail.jar
jar 资源 //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();
    }    
}    

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标系统运维之Exchange频道!

本文由 @白羽 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程