Java implementation of the delivery of mail, including the sending of Web page files

Source: Internet
Author: User
Tags readfile stringbuffer
This article originates from the "Java Development Notes" blog http://gaoqifang.blog.51cto.com/2270113/758306 Description: 1, this program can achieve Web page files, ordinary files sent. 2, the implementation of mail delivery needs three jar package support: Commons-codec-1.3.jar, Commons-httpclient-3.0.jar (these two jar package implementation crawl Internet Web page content) and Mail.jar specific implementation: I. First, the Mailauthenticator class is established and inherits from the Javax.mail.Authenticator class. This class realizes the login verification of the Outbox. Package com.company.simplemail;

Import Javax.mail.Authenticator;

Import javax.mail.PasswordAuthentication;

/**
* Server mailbox Logon Verification
*/
public class Mailauthenticator extends authenticator {

User name (login mailbox)
Private String username;

Password
private String password;

/**
* Initialization of mailboxes and passwords
* @param username Mailbox
* @param password Password
*/
Public Mailauthenticator (string Username, string password) {
This.username = Username;
This.password = password;
}

String GetPassword () {
return password;
}

@Override
Protected Passwordauthentication getpasswordauthentication () {
return new passwordauthentication (username, password);
}

String GetUserName () {
return username;
}

public void SetPassword (String password) {
This.password = password;
}

public void Setusername (String username) {
This.username = Username;
}

Two, the establishment Simplemailsender class, this kind realizes the mail the single, the Mass and so on, is the mail sends the core class. Package com.company.simplemail;

Import java.util.List;
Import java.util.Properties;

Import javax.mail.MessagingException;
Import Javax.mail.Multipart;
Import javax.mail.Session;
Import Javax.mail.Transport;
Import javax.mail.internet.AddressException;
Import javax.mail.internet.InternetAddress;
Import Javax.mail.internet.MimeBodyPart;
Import Javax.mail.internet.MimeMessage;
Import Javax.mail.internet.MimeMessage.RecipientType;
Import Javax.mail.internet.MimeMultipart;


/**
* Simple Mail transmitter, can be single, Mass.
*/
public class Simplemailsender {
Props file to send mail
Private final transient Properties props = system.getproperties ();

Mail server logon Verification
private transient mailauthenticator authenticator;

Mailbox session
private transient session session;

/**
* Initialize Mail transmitter
* @param smtphostname SMTP mail server address
* @param username The name of the user to send the message (address)
* @param password The password to send the message
*/
Public Simplemailsender (final string smtphostname, final string username,
Final String password) {
Init (username, password, smtphostname);
}

/**
* Initialize Mail transmitter
* @param username The user name (address) of the sending message, and resolves the SMTP server address
* @param password The password to send the message
*/
Public Simplemailsender (final string username, final string password) {
Resolves an SMTP server through a mailbox address, which works for most mailboxes
Final String smtphostname = "smtp." + Username.split ("@") [1];
Init (username, password, smtphostname);
}

/**
* Initialization
* @param username The name of the user to send the message (address)
* @param password Password
* @param smtphostname SMTP Host Address
*/
private void init (string username, string password, string smtphostname) {
Initialize Props
Props.put ("Mail.smtp.auth", "true");
Props.put ("Mail.smtp.host", smtphostname);
Verify
Authenticator = new Mailauthenticator (username, password);
Create session
Session = Session.getinstance (props, authenticator);
}

/**
* Send mail
* @param recipient Recipient email Address
* @param subject Mail subject
* @param contents of content messages
* @throws addressexception
* @throws messagingexception
*/
public void Send (string recipient, string subject, string content)
Throws Addressexception, Messagingexception {
Create MIME type messages
Final MimeMessage message = new MimeMessage (session);
Set Sender
Message.setfrom (New InternetAddress (Authenticator.getusername ()));
Set recipient
Message.setrecipient (recipienttype.to, New InternetAddress (recipient));
Set a Theme
Message.setsubject (subject);
Set up message content
Multipart MP = new Mimemultipart ("related");
MimeBodyPart MBP = new MimeBodyPart ();
Mbp.setcontent (Content.tostring (), "text/html;charset=utf-8");
Mp.addbodypart (MBP);
Message.setcontent (MP);


Set up message content
Message.setcontent (Content.tostring (), "text/html;charset=utf-8");
Send
Transport.send (message);
}

/**
* Mass mail
* @param recipients recipients
* @param subject Theme
* @param content
* @throws addressexception
* @throws messagingexception
*/
public void Send (list<string> recipients, string subject, string content)
Throws Addressexception, Messagingexception {
Create MIME type messages
Final MimeMessage message = new MimeMessage (session);
Set Sender
Message.setfrom (New InternetAddress (Authenticator.getusername ()));
Set recipients
final int num = Recipients.size ();
Internetaddress[] addresses = new Internetaddress[num];
for (int i = 0; i < num; i++) {
Addresses[i] = new InternetAddress (Recipients.get (i));
}
Message.setrecipients (recipienttype.to, addresses);
Set a Theme
Message.setsubject (subject);
Set up message content
Message.setcontent (Content.tostring (), "text/html;charset=utf-8");
Send
Transport.send (message);
}

/**
* Send mail
* @param recipient Recipient email Address
* @param mail Message Object
* @throws addressexception
* @throws messagingexception
*
*/
public void Send (String recipient, Simplemail Mail)
Throws Addressexception, Messagingexception {
Send (Recipient, Mail.getsubject (), mail.getcontent ());
}

/**
* Mass mail
* @param recipients recipients
* @param mail Message Object
* @throws addressexception
* @throws messagingexception
*/
public void Send (list<string> recipients, Simplemail Mail)
Throws Addressexception, Messagingexception {
Send (recipients, Mail.getsubject (), mail.getcontent ());
}
Third, the establishment of the Simplemail class, this is just a common message class, mainly used to encapsulate the message to be sent. Package com.company.simplemail;

public class Simplemail {
Topics in a message
Private String subject;
The content of the message (body)
Private String content;
Additional message elements can be added as needed

public void Setsubject (String subject) {
This.subject = subject;
}

public void SetContent (String content) {
this.content = content;
}

Public String Getsubject () {
return subject;
}

Public String getcontent () {
return content;
}
Establish the Readhtmlfile class, which is used to read Web page files (and, of course, to read normal files), and to convert files to string to send

Package com.company.util;

Import Java.io.BufferedInputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.Reader;

Import org.apache.commons.httpclient.HttpClient;
Import org.apache.commons.httpclient.HttpException;
Import Org.apache.commons.httpclient.methods.GetMethod;

public class Readhtmlfile {

public static HttpClient client = new HttpClient ();

Reading normal files
public static string ReadFile (string filename) {
File File = new file (filename);
Reader reader = null;
StringBuffer STB = new StringBuffer ();
int charread = 0;
char[] temps = new char[100];
try {
reader = new InputStreamReader (new FileInputStream (file));
while ((Charread = Reader.read (temps))!=-1) {
if (Charread = = temps.length) {
Stb.append (temps);
Temps = new char[100];
Charread = 0;
}
}
Stb.append (temps);
Reader.close ();
catch (Exception e) {
E.printstacktrace ();
}
String str = stb.tostring ();
return str;
}

/**
*
* To send the page, do not use the external style, script, etc.,
* Because each big mailbox background filter algorithm will filter out the Css,script and so on
* Style is written with the label style property
* Pictures, links must use the absolute address (http://...). ) Form to receive display
* */
public static string GetSource (string url) {

GetMethod method = new GetMethod (URL);

try {
Client.executemethod (method);
catch (HttpException e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
}
InputStream in = null;
try {
in = Method.getresponsebodyasstream ();
catch (IOException E1) {

E1.printstacktrace ();
}
in = new Bufferedinputstream (in);
Reader r = new InputStreamReader (in);
int C;
StringBuffer buffer = new StringBuffer ();

try {
while ((c = r.read ())!=-1)
Buffer.append ((char) c);
catch (IOException e) {
E.printstacktrace ();
}
try {
In.close ();
catch (IOException e) {
E.printstacktrace ();
}
Method.releaseconnection ();

return buffer.tostring ();
}
}
Five, set up the test class, you can send the mail ... Package com.company.simplemail;

Import java.util.ArrayList;
Import java.util.List;

Import Org.junit.Test;

Import Com.company.util.ReadHtmlFile;

public class MailTest {
/**
* Solitary
* */
@Test
public void Testsinglesend () {
Simplemail sm= new Simplemail ();
Sm.setsubject ("first email");
String str = readhtmlfile.getsource ("http://www.baidu.com");
String str = readhtmlfile.readfile ("Fill in the local file path you need to send here");
System.out.println (str);
Sm.setcontent (str);
Simplemailsender sms=new simplemailsender ("Fill your Outbox here", "Fill in your Outbox password");
try {
Sms.send ("Here need to fill in the mail to receive email", SM);
System.out.println ("Execution complete ...") ");
catch (Exception e) {
E.printstacktrace ();
}
}


/**
* Mass
*
* */
@Test
public void Testmasssend () {
Simplemail sm=new Simplemail ();
Sm.setsubject ("first email");
String str = readhtmlfile.getsource ("http://www.baidu.com");
String str = readhtmlfile.readfile ("Fill in the local file path to be sent here");
System.out.println (str);
Sm.setcontent (str);
Simplemailsender sms=new Simplemailsender ("Fill out your Outbox here", "Fill in your Outbox password");
List<string> recipients=new arraylist<string> ();
Recipients.add ("There is a need to fill in the mail to receive email");
Recipients.add ("There is a need to fill in the mail to receive email");
Recipients.add ("There is a need to fill in the mail to receive email");
Recipients.add ("There is a need to fill in the mail to receive email");
try {
Sms.send (recipients, SM);
System.out.println ("Execution complete ...") ");
catch (Exception e) {
E.printstacktrace ();
}
}
}
Finally again stressed: 1, to send the page, do not use the external style, script, etc., because the large mailbox background filtering algorithm will filter out css,script and so on.
2, the style is written with the label style property
3, the picture, the link must use the absolute address (http://...). In order to receive the display 4, generally used to send the page files are according to the above requirements, their own production, specifically for the mail sent pages. Web pages crawled on the internet after sending, generally can not be in the Inbox perfect display

Related Article

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.