你既然用的是EXCHANGE,为什么要用JAVA来写发邮件的程序呢?我这里有我以前用COM+的收发邮件的程序
解决方案 »
- 这句话\u4e13\u5229\u5c40\u6570\u636e\u5bfc\u51fa\u63a7\u5236\u53f0是什么?
- is-a has-a uses-a 什么区别?
- 请教问题,看以下程序,谢谢!
- 怎么把一个很大的double类型的数转换能String类型,不是科学计数法的那种
- ★blue999star(正在学习的星星)、yeli(旗手) 来拿分啊! 谢谢!
- JAVA 中的文本颜色问题
- 怎样将数字进行舍入?
- 这个问题竟然没人能解决?????
- 请问Properties 的void store(OutputStream out,String header)怎么用?
- Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException:
- 怎样设置可以使窗口初始化时为最大窗口?
- 一个接口的继承问题
有机会我们讨论讨论吧!
必须用,因为我们整个系统要支持Linux和Windows
import javax.mail.internet.*;
import java.util.*;public class Assimilator { public static void main(String[] args) { Properties props = new Properties();
props.put("mail.host", "192.168.0.18"); try {
Session mailConnection = Session.getInstance(props, null);
Address bill = new InternetAddress("jike", "yyh");
Address elliotte = new InternetAddress("[email protected]"); Message msg = new MimeMessage(mailConnection);
msg.setFrom(bill);
msg.setRecipient(Message.RecipientType.TO, elliotte);
msg.setSubject("You must comply.");
String[] lang={"i-zh-CN"};
((MimeMessage)msg).setContentLanguage(lang);
msg.setContent("Resistance is futile. 正文",
"text/html");
Transport.send(((MimeMessage)msg));
}
catch (Exception e) {
e.printStackTrace();
}
}}
import java.io.*;
import java.net.UnknownHostException;
import java.util.*;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;public class SMTPMail
{ public SMTPMail()
{
} public String send(String smtp, String from, String password, Date sendDate, String to, String cc, String bcc,
String subject, String body, String attachmentStr[])
throws MessagingException
{
FileDataSource attachmentFile = null;
MimeBodyPart mbp1 = null;
MimeBodyPart mbp2 = null;
MimeBodyPart mbp3 = null;
MimeBodyPart mbp4 = null;
MimeBodyPart mbp5 = null;
MimeBodyPart mbp6 = null;
Properties props = System.getProperties();
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.host", smtp);
Session mailSession = Session.getDefaultInstance(props, null);
MimeMessage mimeMsg = new MimeMessage(mailSession);
mimeMsg.setFrom(new InternetAddress(from));
if(to != null && !to.trim().equals(""))
mimeMsg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to));
if(cc != null && !cc.trim().equals(""))
mimeMsg.setRecipients(javax.mail.Message.RecipientType.CC, InternetAddress.parse(cc));
if(bcc != null && !bcc.trim().equals(""))
mimeMsg.setRecipients(javax.mail.Message.RecipientType.BCC, InternetAddress.parse(bcc));
if(subject == null)
subject = new String("");
mimeMsg.setSubject(subject);
mbp1 = new MimeBodyPart();
if(body == null)
body = new String("");
mbp1.setText(body);
MimeMultipart mp = new MimeMultipart();
if(mbp1 != null)
try
{
mp.addBodyPart(mbp1);
}
catch(MessagingException messagingexception) { }
if(attachmentStr != null)
{
int num = attachmentStr.length;
for(int i = 0; i < num; i++)
{
if(attachmentStr[i] == null)
continue;
try
{
mbp2 = new MimeBodyPart();
attachmentFile = new FileDataSource(attachmentStr[i]);
mbp2.setDataHandler(new DataHandler(attachmentFile));
mbp2.setFileName(attachmentFile.getName());
mp.addBodyPart(mbp2);
}
catch(MessagingException messagingexception1) { }
} }
mimeMsg.setContent(mp);
mimeMsg.setSentDate(sendDate);
System.out.println("Try to send mail...");
System.out.print("Need auth -- ");
System.out.println(props.getProperty("mail.smtp.auth"));
SMTPTransport tr = new SMTPTransport(mailSession, null);
tr.connect(smtp, from, password);
mimeMsg.saveChanges();
tr.sendMessage(mimeMsg, mimeMsg.getAllRecipients());
tr.close();
System.out.println("OK.");
return smtp;
}
public String getTimeIntStr(Date sendDate)
{
return timeIntStr;
} public static void main(String args[])
{
SMTPMail sMail = new SMTPMail();
String atts[] = new String[2];
atts[0] = new String("d:/download/pic/joke.jpg");
GregorianCalendar calen = new GregorianCalendar();
try
{
String a = sMail.send("smtp.eigenet.com", "Vincent<[email protected]>", "", calen.getTime(), "[email protected]", null, null, "hello", "\u4F60\u597D", atts);
System.out.println(a);
}
catch(MessagingException e)
{
Exception nestE = e.getNextException();
System.out.println(e.toString());
if(e == null)
System.out.println(e.toString());
else
if(nestE instanceof UnknownHostException)
System.out.println("SMTP host unapproachable");
else
if(nestE instanceof SendFailedException)
System.out.println("Send mail failed");
}
}
}
import javax.mail.internet.*;
import javax.activation.*;
import java.util.*;
public class Assimilator{
public static void main(String args[]){
int i=0;
System.out.println("on sending");
while(i<=2){
try{
Properties Props=new Properties();
Props.put("mail.smtp.host","sina.com");
Session mailConnection=Session.getInstance(Props,null);
Address bill=new InternetAddress("[email protected]");//this mail address must be true;
Address[] elliotte={new InternetAddress("[email protected]")};
Message msg=new MimeMessage(mailConnection);
msg.setFrom(bill);
msg.setContent("haha,My program is succeesses,\ncan you get my mail?\n","text/plain"); msg.setRecipients(Message.RecipientType.TO,elliotte);
msg.setSubject("You are wellcome");
msg.setSentDate(new Date());
Transport.send(msg);
}catch (Exception e){
e.printStackTrace();
}
i++ ;
System.out.println("Number is:"+i);
}
System.out.println("send successful");
}
}
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.*;
import javax.servlet.http.*;public class WebMailBean implements HttpSessionBindingListener {
Session session = null;
String protocol = null;
String host = null;
int port = -1;
String user = null;
String defaultFrom = null;
Store store = null;
Folder[] folders = null;
String[] folderNames = null;
Folder currentFolder = null;
int currentMessageNumber = 0;
Message currentMessage = null; // Replace "mail.yourisp.com" with an actual
// SMTP server you have permission to use.
public WebMailBean() {
Properties properties = System.getProperties();
properties.put("mail.transport.protocol", "smtp");
properties.put("mail.smtp.host", "mail.your-isp.com");
session = Session.getInstance(properties, null); // session.setDebug(true);
} // Return an array of installed store protocols. public String[] getProtocols() {
Provider[] providers = session.getProviders(); List storeProtocols = new ArrayList(); for (int i = 0; i < providers.length; ++i) {
if (providers[i].getType() == Provider.Type.STORE) {
storeProtocols.add(providers[i].getProtocol());
}
} return (String[]) storeProtocols.toArray(new String[0]);
} // The following property setters (protocol,
// host, port, user, password) are used
// by JSPs in lieu of a constructor. The
// password property needs to be the last
// one set. public void setProtocol(String protocol) {
if (this.protocol == null) {
this.protocol = protocol;
}
} public String getProtocol() {
return this.protocol;
} public void setHost(String host) {
if (this.host == null) {
this.host = host;
}
} public String getHost() {
return this.host;
} public void setPort(int port) {
if (this.port == -1) {
this.port = port;
}
} public int getPort() {
return this.port;
} public void setUser(String user) {
if (this.user == null) {
this.user = user;
}
} public String getUser() {
return this.user;
} // Setting the password initiates a connection. public void setPassword(String password) throws MessagingException {
connect(password);
} // The default from address is initially
// generated using the user and host
// properties. public String getFrom() {
if (defaultFrom == null) {
defaultFrom = user + "@" + host; }
return defaultFrom;
} // For internal use only. void connect(String password) throws MessagingException {
if (store == null) {
store = session.getStore(protocol);
store.connect(host, port, user, password);
cacheFolders();
setFolder("INBOX");
}
} // This can be used by JSPs to determine
// whether the user needs to login. public boolean isConnected() {
if (store != null) {
return store.isConnected(); }
return false;
} // For internal use only. void close() {
if (isConnected()) {
try { // Close all open folders. if (folders != null) {
for (int i = 0; i < folders.length; ++i) {
if (folders[i].isOpen()) {
folders[i].close(true);
}
}
} if (store != null) {
store.close(); }
} catch (MessagingException e) { // Not much we can do here.
}
}
} // Cache all of the folders underneath the default
// folder. This will keep us from constantly
// opening and closing the same folders. void cacheFolders() throws MessagingException {
Folder defaultFolder = store.getDefaultFolder();
Folder[] childFolders = defaultFolder.list(); List availableFolders = new ArrayList(); for (int i = 0; i < childFolders.length; ++i) {
String folderName = childFolders[i].getName(); // Ignore "hidden" folders and INBOX.
// We want to add INBOX to the head of the list. if (!folderName.startsWith(".")
&&!folderName.equalsIgnoreCase("INBOX")) {
availableFolders.add(childFolders[i]);
}
} // Sort the folders by name. Collections.sort(availableFolders, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Folder) o1).getName()
.compareToIgnoreCase(((Folder) o2).getName());
}
}); // Add INBOX as the first folder in the list.
Folder inbox = defaultFolder.getFolder("INBOX"); if (inbox.exists()) {
availableFolders.add(0, inbox); }
folders = (Folder[]) availableFolders.toArray(new Folder[0]);
} // Finds a folder based on name out of our
// cached array of folders.
// For internal use only. Folder findFolder(String folderName) {
for (int i = 0; i < folders.length; ++i) {
if (folders[i].getName().equals(folderName)) {
return folders[i];
}
} return null;
} // Only folders underneath the store's default folder
// can currently be set. public void setFolder(String folderName) throws MessagingException {
currentFolder = findFolder(folderName); if ((!currentFolder.isOpen()) && (currentFolder.exists())
&& ((currentFolder.getType() & Folder.HOLDS_MESSAGES)
!= 0)) {
currentFolder.open(Folder.READ_WRITE);
} currentMessageNumber = 0;
currentMessage = null;
} // Get the current folder's name.
public String getFolderName() {
return currentFolder.getName();
} // Get the names of all the cached folders.
public String[] getFolderNames() {
String[] folderNames = new String[folders.length]; for (int i = 0; i < folders.length; ++i) {
folderNames[i] = folders[i].getName();
} return folderNames;
} // Get the names of all the folders except for the
// current one. This is useful for operations that
// move messages from one folder to any of the other
// available folders. public String[] getOtherFolderNames() {
String[] folderNames = new String[folders.length - 1]; for (int i = 0, j = 0; i < folders.length; ++i) {
if (folders[i] != currentFolder) {
folderNames[j++] = folders[i].getName();
}
} return folderNames;
}
public int getMessageCount() throws MessagingException {
return currentFolder.getMessageCount();
} // Use this to loop over the non-deleted
// messages in the current folder.
public boolean getNextMessage() throws MessagingException {
int messageCount = currentFolder.getMessageCount(); for (int i = currentMessageNumber + 1; i <= messageCount; ++i) {
Message nextMessage = currentFolder.getMessage(i); if (!nextMessage.isSet(Flags.Flag.DELETED)) {
currentMessageNumber = i;
currentMessage = nextMessage; return true;
}
} return false;
} // Set the bean's current message to the specified number.
// Pass in 0 to reset the current message pointer.
public void setMessage(int messageNumber)
throws MessagingException {
if (messageNumber == 0) {
currentMessageNumber = messageNumber;
currentMessage = null; } else {
currentMessageNumber = messageNumber - 1;
getNextMessage();
}
} // Get the current message's number.
public int getMessageNumber() {
return currentMessage.getMessageNumber();
} // Get the current message's sent date as a string.
public String getMessageSentDate() throws MessagingException {
Date sentDate = currentMessage.getSentDate(); if (sentDate != null) {
return sentDate.toString();
} else {
return "Date unknown";
}
} // Get the current message's first from address or
// reply-to address as a string.
public String getMessageFrom() throws MessagingException {
Address[] addresses = currentMessage.getFrom(); if (addresses == null) {
addresses = currentMessage.getReplyTo(); }
if (addresses.length > 0) {
return addresses[0].toString(); }
return "";
} // Get the current message's first reply-to address
// as a string.
public String getMessageReplyTo() throws MessagingException {
Address[] addresses = currentMessage.getReplyTo(); if (addresses.length > 0) {
return addresses[0].toString(); }
return "";
} // Get the current message's first to address as a string. public String getMessageTo() throws MessagingException {
Address[] addresses =
currentMessage.getRecipients(Message.RecipientType.TO); if (addresses != null && addresses.length > 0) {
return addresses[0].toString(); }
return "";
} // Get the current message's subject. public String getMessageSubject() throws MessagingException {
String subject = currentMessage.getSubject(); if (subject == null) {
subject = ""; }
return subject;
} // Get the current message's size as an
// abbreviated string. public String getMessageSize() throws MessagingException {
String size = "?"; int bSize = currentMessage.getSize(); if (bSize != -1) {
if (bSize >= 1024 * 1024) {
int mbSize = bSize / (1024 * 1024);
size = mbSize + " MB"; } else if (bSize >= 1024) {
int kbSize = bSize / 1024;
size = kbSize + " KB"; } else {
size = bSize + " Bytes";
}
} return size;
} // Get the text for this message. This only works
// if the message's primary type is "text"
// or if it's "multipart" and the first body
// part's primary type is text.
public String getMessageText()
throws IOException, MessagingException {
String text = currentMessage.getContentType(); if (currentMessage.isMimeType("text/*")) {
text = (String) currentMessage.getContent();
} else if (currentMessage.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) currentMessage.getContent();
BodyPart firstPart = multipart.getBodyPart(0); if (firstPart.isMimeType("text/*")) {
text = (String) firstPart.getContent();
}
} return text;
} // Turn an array of message numbers as strings
// into an array of messages from the current
// folder. This can be used for commands that
// act on multiple messages like delete, copy,
// and move.
// For internal use only. Message[] findMessages(String[] messageNumbers)
throws MessagingException {
if (messageNumbers != null) {
List messageList = new ArrayList(); for (int i = 0; i < messageNumbers.length; ++i) {
int messageNumber = 0; try {
messageNumber = Integer.parseInt(messageNumbers[i]); } catch (NumberFormatException e) {
messageNumber = 0;
} if (messageNumber > 0) {
messageList.add(currentFolder.getMessage(messageNumber));
}
} return (Message[]) messageList.toArray(new Message[0]);
} return new Message[0];
}
// Perform a specialized command. The request's parameters
// should contain a value named "command" and an array of
// message numbers called "number".
// The copy and move commands need a folder name in
// the "to" parameter.
// The send command needs from, to, cc, bcc, subject,
// and text parameters. It can also have a reply parameter
// that indicates the message should be a reply to
// an existing message in the current folder.
// This isn't very elegant but it's better than
// putting the code in a JSP.
public void doCommand(HttpServletRequest request)
throws MessagingException {
String command = request.getParameter("command");
String[] messageNumbers = request.getParameterValues("number");
String toFolderName = request.getParameter("to");
Folder toFolder = findFolder(toFolderName);
if ("Copy".equalsIgnoreCase(command)) {
if (toFolder != null) {
Message[] messages = findMessages(messageNumbers);
currentFolder.copyMessages(messages, toFolder);
}
} else if ("Move".equalsIgnoreCase(command)) {
if (toFolder != null) {
Message[] messages = findMessages(messageNumbers);
currentFolder.copyMessages(messages, toFolder);
currentFolder.setFlags(messages,
new Flags(Flags.Flag.DELETED), true);
}
} else if ("Delete".equalsIgnoreCase(command)) {
Message[] messages = findMessages(messageNumbers);
currentFolder.setFlags(messages, new Flags(Flags.Flag.DELETED),true);
} else if ("Send".equalsIgnoreCase(command)) {
defaultFrom = request.getParameter("from");
String to = request.getParameter("to");
String cc = request.getParameter("cc");
String bcc = request.getParameter("bcc");
String subject = request.getParameter("subject");
String text = request.getParameter("text");
String reply = request.getParameter("reply");
Message message = null;
int replyNumber = 0;
try {
replyNumber = Integer.parseInt(reply); } catch (NumberFormatException e) {}
if (replyNumber > 0) {
message = currentFolder.getMessage(replyNumber).reply(false);
} else {
message = new MimeMessage(session);
}
message.setFrom(new InternetAddress(defaultFrom));
if (to != null) {
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
}
if (cc != null) {
message.setRecipients(Message.RecipientType.CC,
InternetAddress.parse(cc));
}
if (bcc != null) {
message.setRecipients(Message.RecipientType.BCC,
InternetAddress.parse(bcc));
}
message.setSubject(subject);
message.setText(text);
Transport.send(message);
}
}
// HttpSessionBindingListener methods
public void valueBound(HttpSessionBindingEvent event) {}
// Close the store when the session ends.
public void valueUnbound(HttpSessionBindingEvent event) {
close();
}
}
import javax.mail.internet.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class SMTPClient extends JFrame { private JButton sendButton = new JButton("Send Message");
private JLabel fromLabel = new JLabel("From: ");
private JLabel toLabel = new JLabel("To: ");
private JLabel hostLabel = new JLabel("SMTP Server: ");
private JLabel subjectLabel = new JLabel("Subject: ");
private JTextField fromField = new JTextField(40);
private JTextField toField = new JTextField(40);
private JTextField hostField = new JTextField(40);
private JTextField subjectField = new JTextField(40);
private JTextArea message = new JTextArea(40, 72);
private JScrollPane jsp = new JScrollPane(message); public SMTPClient() {
super("SMTP Client");
Container contentPane = this.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel labels = new JPanel();
labels.setLayout(new GridLayout(4, 1));
labels.add(hostLabel);
JPanel fields = new JPanel();
fields.setLayout(new GridLayout(4, 1));
String host = System.getProperty("mail.host", "");
hostField.setText(host);
fields.add(hostField);
labels.add(toLabel);
fields.add(toField); String from = System.getProperty("mail.from", "");
fromField.setText(from);
labels.add(fromLabel);
fields.add(fromField); labels.add(subjectLabel);
fields.add(subjectField);
Box north = Box.createHorizontalBox();
north.add(labels);
north.add(fields);
contentPane.add(north, BorderLayout.NORTH);
message.setFont(new Font("Monospaced", Font.PLAIN, 12));
contentPane.add(jsp, BorderLayout.CENTER); JPanel south = new JPanel();
south.setLayout(new FlowLayout(FlowLayout.CENTER));
south.add(sendButton);
sendButton.addActionListener(new SendAction());
contentPane.add(south, BorderLayout.SOUTH);
this.pack();
} class SendAction implements ActionListener {
public void actionPerformed(ActionEvent evt) {
try {
Properties props = new Properties();
props.put("mail.host", hostField.getText());
Session mailConnection = Session.getInstance(props, null);
final Message msg = new MimeMessage(mailConnection);
Address to = new InternetAddress(toField.getText());
Address from = new InternetAddress(fromField.getText());
msg.setContent(message.getText(), "text/plain");
msg.setFrom(from);
msg.setRecipient(Message.RecipientType.TO, to);
msg.setSubject(subjectField.getText());
// This can take a non-trivial amount of time so
// spawn a thread to handle it.
Runnable r = new Runnable() {
public void run() {
try {
Transport.send(msg);
}
catch (Exception e) {
e.printStackTrace();
}
}
};
Thread t = new Thread(r);
t.start();
message.setText("");
}
catch (Exception e) {
// We should really bring up a more specific error dialog here.
e.printStackTrace();
}
}
} public static void main(String[] args) { SMTPClient client = new SMTPClient();
// Next line requires Java 1.3. We want to set up the
// exit behavior here rather than in the constructor since
// other programs that use this class may not want to exit
// the application when the SMTPClient window closes.
client.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.show(); }}
java.lang.NoClassDefFoundError: javax/mail/Message
我估计是环境配置的问题,那位能给我一个具体的能够跑通jsp下发邮件的具体配置?