1. Create a new Java project, SendMail.
2. Introduction of three jars.
Create a new folder Lib in the project, copy three jars, and import->order and export√ on the Properties->java build Path->librarys.
Commons-email-1.2.jar
Activation-1.1.jar
Mail-1.4.jar (the jar was not introduced at first, the result is an error, java.lang.NoClassDefFoundError:javax.mail.Authenticator)
3. Create a new class Sendmail.java
Package com.ibm.docs.viewer;
Import org.apache.commons.mail.EmailException;
Import Org.apache.commons.mail.SimpleEmail;
public class SendMail {public
SendMail () {
} public
static void Main (string[] args) {
send ();
System.out.println ();
}
public static void Send () {
Simpleemail email = new Simpleemail ();
Email.settls (true);
Email.sethostname ("d23m0037.cn.ibm.com");
Email.setauthentication ("XXX@cn.ibm.com", "XXXX"); Username and password
try {
email.addto ("XXXX@qq.com");//receiver
Email.setfrom ("XXXX@cn.ibm.com");//Sender
Email.setsubject ("Java Mail Test"); Title
email.setmsg ("Just a simple send test.");//Content
email.send ();
} catch (Emailexception e) {
e.pr Intstacktrace ();}}
4. Run.
Before using the 163,gmail, Sina's mail server all error.
Sending the email to the following server failed
Online search should be the company's port 25 has been sealed,
Start-run-cmd-type command Netstat-an only see the open port on this machine
At the time of the test, we found that Telnet d23m0037.cn.ibm.com 25 was a good indication that the server was successful and received the message successfully.
5. Send a message with an attachment.
Package com.ibm.docs.viewer;
Import org.apache.commons.mail.EmailAttachment;
Import org.apache.commons.mail.EmailException;
Import Org.apache.commons.mail.MultiPartEmail; public class Sendattachment {public static void main (string[] args) throws emailexception {multipartemail email = NE
W Multipartemail ();
Send mail via IBM Server EMAIL.SETTLS (TRUE); Email.sethostname ("d23m0037.cn.ibm.com"); Set SMTP Server Email.setauthentication ("XXX@cn.ibm.com", "xxx@2012");
Username and password Emailattachment attachment = new Emailattachment ();
Attachment.setpath ("C:\\Documents and Settings\\administrator\\my documents\\downloads\\result.txt");
Attachment.setdisposition (emailattachment.attachment)//Set attachment (inline, attachment) attachment.setdescription ("result"); Attachment.setname ("Result.txt"); The file name of the attachment email.addto ("XXX@qq.com"); Receiving party Email.setfrom ("XXX@cn.ibm.com"); Sender Email.setsubject ("Java Mail Test"); Title Email.setmsg ("Just a simple send test."); Content Email.attach (AttachmENT);
Email.send ();
}
}
I've written a 163-based, a year ago, and forgot, damn it.
Write it down now, and maybe you can use it later. You can reuse the code. o Yes.