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();
}
}