JavaMail Implement email mail Sending program code

Source: Internet
Author: User

Basic knowledge of JavaMail
using JavaMail is the component you need to send e-mail.
JavaMail's organization makes it easy to process e-mail. Some of the classes we need are listed below:
1. Properties

JavaMail requires properties to create a Session object. It will look for the string "Mail.smtp.host", the property value being the host that sent the message, such as:
Properties Props = new properties ();
Props.put ("Mail.smtp.host", "smtp.abcd.com");//Can be replaced with your SMTP host name.
2. Session

This session class represents a message session in JavaMail. Each JavaMail application has at least one session but can have any number of sessions. In this example, the session object needs to know the SMTP server that is used to process the message. To do this, you can use properties to create a Session object with reference to the following example
Session sendmailsession;
Sendmailsession = session.getinstance (props, null);
3. Transport

Messages are either sent or can be received. JavaMail uses two different classes to accomplish these two functions:
Transport and Store. Transport is used to send information, and the store is used to collect letters. For this tutorial we only need to use the transport object. Please refer to Sun's JavaMail documentation for Store usage.
Usage: transport transport;
Transport = Sendmailsession.gettransport ("SMTP");
Initializes the transport with the Gettransport method of the JavaMail session object. A string that passes past declares the protocol to use for the object, such as "SMTP." This will save us a lot of time. Because JavaMail has a lot of protocols implemented in the Territory.
Note: JavaMail does not absolutely support each protocol and currently supports IMAP, SMTP, and POP3.
4. Message

The Message object stores the e-mail messages we actually send, and the messages object is created as a MimeMessage object and needs to know which JavaMail session should be chosen.
The use method is: Message Newmessage = new MimeMessage (sendmailsession);
My program implementation of the main features, in addition to (1) can normally send text messages, (2) can also send attachments, (3) Now most mail servers require the login line authentication, so this program has required this function. (4) In addition, for the convenience of users, the SMTP server is required to be configured only for the first time, using direct read from the configuration file later.
Writing Program code
Here is the code that implements the above features

The code is as follows Copy Code
MIME Mail Object
MimeMessage mimemsg = null;
Mail Session Object
Session session = NULL;
Properties props = System.getproperties (); Get System Properties
Props.put ("Mail.smtp.host", mailhost); Setting up an SMTP host
Get mail Session Object
Session = Session.getdefaultinstance (props,null);
To create a MIME mail object
mimemsg = new MimeMessage (session);
Set Sender
Mimemsg.setfrom (New InternetAddress (from));
Set up the addressee.
if (to!=null) {
Mimemsg.setrecipients (Message.RecipientType.TO, Internetaddress.parse (to));
}
Set CC person
if (cc!=null) {
Mimemsg.setrecipients (Message.RecipientType.CC, Internetaddress.parse (CC));
}
Set the dark to send people
if (bcc!=null) {
Mimemsg.setrecipients (Message.RecipientType.BCC, Internetaddress.parse (BCC));
}
Set Message subject
Mimemsg.setsubject (Subject, "GBK");
Set up message content
Mimemsg.settext (Content, "GBK");
Date Sent
Mimemsg.setsentdate (New Date ());
Send mail
Transport.send (MIMEMSG);
System.out.println ("Email send! ");
catch (Exception e) {
E.printstacktrace ();
}
The following code is used to send attachments
To send an attachment, you need to define the file name string filename sends the attachment as the second part of the letter content. So make a slight change to the code above.
Part I. Information
MimeBodyPart MBP1 = new MimeBodyPart ();
Mbp1.settext (Content, "GBK");
Part II Information
MimeBodyPart MBP2 = new MimeBodyPart ();
Attach a file to the second part of the information
Filedatasource FDS = new Filedatasource (fileattachment);
Mbp2.setdatahandler (New DataHandler (FDS));
Mbp2.setfilename (Fds.getname ());
}
Create Multipart and put each MimeBodyPart
Multipart MP = new Mimemultipart ();
Mp.addbodypart (MBP1);
Mp.addbodypart (MBP2);
Increase Multipart to the information body
Mimemsg.setcontent (MP);

Most mail servers now require authentication, and authentication with JavaMail is simple.
The first authentication requires a new class Email_autherticatorbean. This class to use for authenticated messages, this class must inherit the authenticator class and overwrite the Getpasswordauthentication method
The code for the Email_autherticatorbean class is as follows

The code is as follows Copy Code
Import javax.mail.*;
public class Email_autherticatorbean extends javax.mail.authenticator{
Private String m_username = null;
Private String m_userpass = null;
public void Setusername (String username) {
M_username = Username;
}
public void Setuserpass (String userpass) {
M_userpass = Userpass;
}
Public Email_autherticatorbean () {
Super ();
}
Public Email_autherticatorbean (string username, string userpass) {
Super ();
Setusername (username);
Setuserpass (Userpass);
}
Automatically invoked when authentication is required
Public Passwordauthentication getpasswordauthentication () {
return new Passwordauthentication (M_username,m_userpass);
}
}

Calling this class in the main function verifies identity, but you need to make some changes to code 1.
Define user name and password variable String user=null; String Password=null;
Need to add a statement to set up authentication

The code is as follows Copy Code
Props.put ("Mail.smtp.host", mailhost); Setting up an SMTP host
Props.put ("Mail.smtp.auth", "true"); Set authentication to TRUE, if authentication must be set to TRUE//Get mail Session Object
Session = Session.getdefaultinstance (props,null) in code 1; To
Session = Session.getdefaultinstance (props, new Email_autherticatorbean (user, password));

The above changes can complete the authentication function.
Read and write to configuration file
So to use the Java IO Stream, you need to java.io the package. When the program is started, read the information from the file, do not change the configuration once, write the new settings to the file.
Write Data

The code is as follows Copy Code
try {
BufferedWriter out = new BufferedWriter (
New OutputStreamWriter (New FileOutputStream ("Conf.txt"));
Out.write (STRSMTP);
Out.write ("R");
Out.write (strUserName);
Out.write ("R");
Out.write (strpassword);
Out.close ();
}catch (IOException D)
{}

Reading data: Putting data in a file into an array

  code is as follows copy code
try {
    string[] aa = {"", "", ""};
    String S;
    int i = 0;
    BufferedReader in = new BufferedReader (new InputStreamReader) (New FileInputStream ("Conf.txt")) ;
    while ((s = in.readline ())!= null) {
        aa[i] = s;         i++;
   }
}
catch (IOException D) {}

The above code, you can achieve the basic functions of this program. A graphical interface is also needed to facilitate user use. Java also provides a powerful visual programming class library, Swing class, and AWT classes. and the JBUILDER9 integrated development environment, has the very good UI design function, may very conveniently design the beautiful graphical interface.
So the next thing to do is to add the code of the functional module to it. If you add code 1 to the event handler function of the Send button, send the letter whenever you press the button.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.