Java Mail Send mail

Source: Internet
Author: User

Recently did the automatic Send mail feature, with attachments: The required jar package has, if the development tool for MyEclipse there is a conflict,

The original mail jar package for myeclipse should be deleted;

Open Javaee.jar, delete the original mail folder, and then restart MyEclipse!

The code is as follows:

Package com.noahwm.bigscreen.exportexcel;

Import Java.util.Date;
Import java.util.Enumeration;
Import java.util.Properties;
Import Java.util.Vector;

Import javax.activation.*;
Import Javax.mail.Authenticator;
Import Javax.mail.Message;
Import Javax.mail.Multipart;
Import javax.mail.PasswordAuthentication;
Import javax.mail.Session;
Import Javax.mail.Transport;
Import javax.mail.internet.InternetAddress;
Import Javax.mail.internet.MimeBodyPart;
Import Javax.mail.internet.MimeMessage;
Import Javax.mail.internet.MimeMultipart;
Import javax.mail.internet.MimeUtility;

Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import java.text.ParseException;
Import Java.text.SimpleDateFormat;
Import java.util.ArrayList;
Import Java.util.Date;
Import Java.util.HashSet;
Import Java.util.Iterator;
Import java.util.List;
Import Java.util.Locale;
Import Java.util.Set;
Import Java.util.regex.Pattern;



/**
* <p>
* Title: Send mail using JavaMail
* </p>
*/
public class Mailutils {

String to = "";//Recipient
String from = "";//Sender
String host = "";//SMTP hosts
String username = "";
String password = "";
String filename = "";//Attachment file name
String subject = "";//Message subject
String content = "";//Message body
Vector file = new vector ();//Attachment file Collection



/**
* <br>
* Method Description: Default constructor <br>
* Input Parameters: <br>
* Return type:
*/
Public Mailutils () {
}

/**
* <br>
* Method Description: Constructor, provide direct parameter incoming <br>
* Input Parameters: <br>
* Return type:
*/
Public Mailutils (string to, string from, String smtpserver,
String Username, string password, string subject, string content) {
This.to = to;
This.from = from;
This.host = SmtpServer;
This.username = Username;
This.password = password;
This.subject = subject;
this.content = content;
}

/**
* <br>
* Method Description: Set mail server address <br>
* Input parameters: String host Mail server address name <br>
* Return type:
*/
public void Sethost (String host) {
This.host = host;
}

/**
* <br>
* Method Description: Set the login server check password <br>
* Input Parameters: <br>
* Return type:
*/
public void SetPassword (String pwd) {
This.password = pwd;
}

/**
* <br>
* Method Description: Set the login server check user <br>
* Input Parameters: <br>
* Return type:
*/
public void Setusername (String USN) {
This.username = USN;
}

/**
* <br>
* Method Description: Set Email destination email <br>
* Input Parameters: <br>
* Return type:
*/
public void Setto (String to) {
This.to = to;
}

/**
* <br>
* Method Description: Set mail send source mailbox <br>
* Input Parameters: <br>
* Return type:
*/
public void Setfrom (String from) {
This.from = from;
}

/**
* <br>
* Method Description: Set Mail subject <br>
* Input Parameters: <br>
* Return type:
*/
public void Setsubject (String subject) {
This.subject = subject;
}

/**
* <br>
* Method Description: Set the message content <br>
* Input Parameters: <br>
* Return type:
*/
public void SetContent (String content) {
this.content = content;
}

/**
* <br>
* Method Description: Convert the theme to Chinese <br>
* Input parameters: String strText <br>
* Return type:
*/
public string Transferchinese (string strText) {
try {
StrText = Mimeutility.encodetext (New String (Strtext.getbytes (),
"gb2312"), "gb2312", "B");
} catch (Exception e) {
E.printstacktrace ();
}
return strText;
}

/**
* <br>
* Method Description: Add attachments to the attachment combination <br>
* Input Parameters: <br>
* Return type:
*/
public void Attachfile (String fname) {
File.addelement (fname);
}

/**
* <br>
* Method Description: Send mail <br>
* Input Parameters: <br>
* Return Type: Boolean success is true, and vice versa is False
*/
public Boolean sendMail () {

Construct Mail session
Properties Props = new properties ();
Props.put ("Mail.smtp.host", host);
Props.put ("Mail.smtp.auth", "true");
Session session = Session.getdefaultinstance (props,
New Authenticator () {
Public Passwordauthentication getpasswordauthentication () {
return new passwordauthentication (username, password);
}
});
Session session = Session.getdefaultinstance (props);
Session session = Session.getdefaultinstance (props, null);

try {
Constructs a mimemessage and sets a basic value
MimeMessage msg = new MimeMessage (session);
MimeMessage msg = new MimeMessage ();
Msg.setfrom (New InternetAddress (from));


Msg.addrecipients (Message.RecipientType.TO, address); This can only be sent to a single person email
Msg.setrecipients (Message.RecipientType.BCC, Internetaddress.parse (to));
Subject = Transferchinese (subject);

Msg.setsubject (subject);

Construction multipart
Multipart MP = new Mimemultipart ();

Add body to multipart
MimeBodyPart mbpcontent = new MimeBodyPart ();
Mbpcontent.setcontent (Content, "text/html;charset=gb2312");

Add to MimeMessage (multipart representative body)
Mp.addbodypart (mbpcontent);

Add an attachment to a multipart
Enumeration efile = File.elements ();
while (Efile.hasmoreelements ()) {

MimeBodyPart mbpfile = new MimeBodyPart ();
filename = Efile.nextelement (). toString ();
Filedatasource FDS = new Filedatasource (filename);
Mbpfile.setdatahandler (New DataHandler (FDS));
This method can solve the attachment garbled problem.
String Filename= new String (Fds.getname (). GetBytes ("gb2312"), "iso8859-1");


Mbpfile.setfilename (filename);
Add to MimeMessage (multipart on behalf of attachment)
Mp.addbodypart (Mbpfile);

}

File.removeallelements ();
Add MimeMessage to multipart
Msg.setcontent (MP);
Msg.setsentdate (New Date ());
Msg.savechanges ();
Send mail

Transport Transport = Session.gettransport ("SMTP");
Transport.connect (host, username, password);
Transport.sendmessage (MSG, msg.getallrecipients ());
Transport.close ();
} catch (Exception Mex) {
Mex.printstacktrace ();
Exception ex = null;
if (ex = Mex.getnextexception ()) = null) {
Ex.printstacktrace ();
//          }
return false;
}
return true;
}



/**
* <br>
* Method Description: Main method, for testing <br>
* Input Parameters: parameter self-filling <br>
* Return type:
*/
public static void Main (string[] args) {
Mailutils sendmail = new Mailutils ();

Mail server
Sendmail.sethost ("xxxx.xx.com");
User name
Sendmail.setusername ("xxxx");
Password
Sendmail.setpassword ("xxxx");
Receiving party
Sendmail.setto ([email protected]);
Sending party
Sendmail.setfrom ("[email protected]");
Title
Sendmail.setsubject ("Mail Header");
Message content
Sendmail.setcontent ("hi!man~~");
String FilePath = "D://xx.txt";
Attachment
Sendmail.attachfile (FilePath);
if (Sendmail.sendmail ()) {
System.out.println ("--------------automatic Mail sending------------successfully");
Delete original file
Boolean flag = DeleteFile (FilePath);
if (flag) {
System.out.println ("--------------original file deletion succeeded-------------");
}else{
System.out.println ("--------------Original file deletion failed-------------");
}
}else{
System.out.println ("--------------automatic Mail Failure-------------");
}
}


public static Boolean DeleteFile (String spath) {
Boolean flag = false;
File File = new file (spath);
The path is a file and is not empty to delete
if (File.isfile () && file.exists ()) {
File.delete ();
Flag = true;
}
return flag;
}
}

Java Mail Send mail

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.