JavaMail Send mail

Source: Internet
Author: User
Tags auth contains mail
Send Mail/*
In the Java version, you often see people asking how to send messages with JavaMail. How do I receive mail? How to access multiple folders, and so on. Problems are scattered, and the response to history has long been submerged in the ocean of problems.

I have done a Java project, which contains a webmail function, the original for the use of Java to javamail groping for some time, finally a little harvest. See the Forum often have this aspect of the problem, so put some of my experience to post out, I hope that some help.

This article only describes the use of JavaMail to implement the Send mail function, which involves SMTP authentication, mail attachment sent, and HTML content mail.
Other information about the implementation of multiple mailboxes, receive POP3 mail and IMAP and other content, will be introduced in subsequent articles.

The following program needs: JAVAMAIL,JAF package, J2ee.jar contains the above two packages, we recommend that you install J2sdkee or direct copy J2ee.jar, add it to the JBuilder library, or system classpath

*/



Package com.me.util.mail;

/**
* @author Zhangkun aistill@msn.com
* @version 1.0
*/

Import java.util.*;
Import javax.mail.*;
Import javax.mail.internet.*;
Import Java.util.Date;
Import javax.activation.*;
Import java.io.*;
Import com.me.util.*;

public class SendMail {

Private MimeMessage mimemsg; MIME Mail Object

Private session session; Mail Session Object
Private Properties props; System Properties
Private Boolean Needauth = false; Does SMTP require authentication

Private String username = ""; SMTP authenticated user name and password
Private String Password = "";

Private Multipart MP; Multipart objects, message content, headers, attachments, and so on are added to it before the MimeMessage object is generated



/**
*
*/
Public SendMail () {
Setsmtphost (getconfig.mailhost)//If no mail server is specified, obtain from the GetConfig class
Createmimemessage ();
}

Public SendMail (String SMTP) {
Setsmtphost (SMTP);
Createmimemessage ();
}



/**
* @param hostName String
*/
public void Setsmtphost (String hostName) {
SYSTEM.OUT.PRINTLN ("Set system properties: Mail.smtp.host =" +hostname);
if (props = = null) props = System.getproperties (); Get System Properties Object

Props.put ("Mail.smtp.host", hostName); Setting up an SMTP host
}


/**
* @return Boolean
*/
public boolean createmimemessage ()
{
try{
System.out.println ("Ready to get mail Session Object!") ");
Session = Session.getdefaultinstance (props,null); Get mail Session Object
}
catch (Exception e) {
SYSTEM.ERR.PRINTLN ("An error occurred while getting the mail session Object!") "+e);
return false;
}

SYSTEM.OUT.PRINTLN ("Prepare to create MIME mail Object!") ");
try{
mimemsg = new MimeMessage (session); To create a MIME mail object
MP = new Mimemultipart ();

return true;
}
catch (Exception e) {
System.err.println ("Create MIME mail object failed!") "+e);
return false;
}
}



/**
* @param need Boolean
*/
public void Setneedauth (Boolean need) {
System.out.println ("Set SMTP identity authentication: Mail.smtp.auth =" +need);
if (props = = null) props = System.getproperties ();

if (need) {
Props.put ("Mail.smtp.auth", "true");
}else{
Props.put ("Mail.smtp.auth", "false");
}
}



/**
* @param name String
* @param pass String
*/
public void Setnamepass (String name,string pass) {
Username = name;
Password = pass;
}


/**
* @param mailsubject String
* @return Boolean
*/
public boolean setsubject (String mailsubject) {
SYSTEM.OUT.PRINTLN ("Set message subject!") ");
try{
Mimemsg.setsubject (Mailsubject);
return true;
}
catch (Exception e) {
SYSTEM.ERR.PRINTLN ("Set Message subject Error!") ");
return false;
}
}



/**
* @param mailbody String
*/
public boolean setbody (String mailbody) {
try{
BodyPart bp = new MimeBodyPart ();
Bp.setcontent ("<meta http-equiv=content-type content=text/html; Charset=gb2312> "+mailbody", "text/html;charset=gb2312");
Mp.addbodypart (BP);

return true;
}
catch (Exception e) {
SYSTEM.ERR.PRINTLN ("error when setting message body!") "+e);
return false;
}
}


/**
* @param name String
* @param pass String
*/
public boolean addfileaffix (String filename) {

System.out.println ("Add Mail attachment:" +filename);

try{
BodyPart bp = new MimeBodyPart ();
Filedatasource fileds = new Filedatasource (filename);
Bp.setdatahandler (New DataHandler (fileds));
Bp.setfilename (Fileds.getname ());

Mp.addbodypart (BP);

return true;
}
catch (Exception e) {
System.err.println ("Add Mail attachment:" +filename+) error occurred! "+e);
return false;
}
}



/**
* @param name String
* @param pass String
*/
public boolean Setfrom (String from) {
System.out.println ("Set sender!") ");
try{
Mimemsg.setfrom (New InternetAddress (from)); Set Sender
return true;
}
catch (Exception e)
{return false;}
}


/**
* @param name String
* @param pass String
*/
public boolean Setto (String to) {
if (to = = null) return false;

try{
Mimemsg.setrecipients (To) (Message.recipienttype.to,internetaddress.parse);
return true;
}
catch (Exception e)
{return false;}

}

/**
* @param name String
* @param pass String
*/
public boolean Setcopyto (String CopyTo)
{
if (CopyTo = null) return false;
try{
Mimemsg.setrecipients (Message.RecipientType.CC, (address[]) Internetaddress.parse (CopyTo));
return true;
}
catch (Exception e)
{return false;}
}


/**
* @param name String
* @param pass String
*/
public boolean sendout ()
{
try{
Mimemsg.setcontent (MP);
Mimemsg.savechanges ();
SYSTEM.OUT.PRINTLN ("Sending mail ...");

Session mailsession = Session.getinstance (props,null);
Transport transport = Mailsession.gettransport ("SMTP");
Transport.connect ((String) props.get ("Mail.smtp.host"), Username,password);
Transport.sendmessage (Mimemsg,mimemsg.getrecipients (Message.RecipientType.TO));
Transport.send (MIMEMSG);

SYSTEM.OUT.PRINTLN ("Send mail successful!") ");
Transport.close ();

return true;
}
catch (Exception e)
{
SYSTEM.ERR.PRINTLN ("Send mail failed!") "+e);
return false;
}
}


/**
* Just do it as this
*/
public static void Main (string[] args) {

String mailbody = "<meta http-equiv=content-type content=text/html; Charset=gb2312> "+
"<div align=center><a href=http://www.csdn.net> csdn </a></div>";

SendMail themail = new SendMail ("smtp.msn.com");
Themail.setneedauth (TRUE);

if (Themail.setsubject ("title") = = false) return;
if (themail.setbody (mailbody) = = false) return;
if (Themail.setto ("gates@msn.com") = = false) return;
if (Themail.setfrom ("bill@msn.com") = = false) return;
if (Themail.addfileaffix ("c:\\boot.ini") = = false) return;
Themail.setnamepass ("User", "password");

if (themail.sendout () = = false) return;
}
}


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.