Java Send mail

Source: Internet
Author: User
Tags base64

This article transferred from: http://www.cnblogs.com/yejg1212/archive/2013/06/01/3112702.html#undefined

The process of implementing Java to send mail is generally the following steps:

    1. Prepare a properties file that holds parameters such as the SMTP server address.
    2. Create a Session object with properties
    3. Create a Message object with session and set the subject and body
    4. Send mail with Transport object

There are 2 jars required: Activation.jar and Mail.jar

See a demo code directly

#----------------These two are the fields----------#smtp服务器mail that must be built for the session. smtp.host=smtp.qq.com# Authentication mail.smtp.auth=true#------ --------------------------------------------------------#发送者的邮箱用户名 [Email protected]# Sender's Email password mail.sender.password=xxxxxxxxxx

#----------------These two are the fields----------#smtp服务器mail that must be built for the session. smtp.host=smtp.qq.com# Authentication mail.smtp.auth=true#------ --------------------------------------------------------#发送者的邮箱用户名 [Email protected]# Sender's Email password mail.sender.password=xxxxxxxxxx

Here is the Java code to send the message

Import Java.io.ioexception;import java.io.inputstream;import Java.util.properties;import Javax.mail.Message;import Javax.mail.messagingexception;import Javax.mail.session;import Javax.mail.transport;import Javax.mail.internet.internetaddress;import Javax.mail.internet.mimemessage;import The Javax.mail.internet.mimeutility;public class JavaMail {/** * Message object stores the e-mail messages that we actually send, and the message object is used as a mimeme     Ssage object to create and need to know which JavaMail session should be selected.        */private MimeMessage message;     /** * Session class represents a mail session in JavaMail.     * Each JavaMail-based application has at least one session (can have any number of sessions).     * * JavaMail requires properties to create a Session object.        * Find "Mail.smtp.host" attribute value is the host sending the message * looking for "Mail.smtp.auth" authentication, the current free mail server requires this item */private session session; /*** * 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 messages, while store is used to receive letters.     For this tutorial we only need to use the transport object.        */Private Transport Transport;    Private String mailhost= ""; Private String SenDer_username= "";        Private String sender_password= "";    Private Properties Properties = new properties (); /* * Initialization method */Public JavaMail (Boolean debug) {InputStream in = JavaMail.class.getResourceAsStream ("Mail        Server.properties ");            try {properties.load (in);            This.mailhost = Properties.getproperty ("Mail.smtp.host");            This.sender_username = Properties.getproperty ("Mail.sender.username");        This.sender_password = Properties.getproperty ("Mail.sender.password");        } catch (IOException e) {e.printstacktrace ();        } session = Session.getinstance (properties);    Session.setdebug (debug);//debug message after open message = new MimeMessage (session); /** * Send mail * * @param subject * Email subject * @param sendhtml * Email content * @p            Aram Receiveuser * Recipient address */public void Dosendhtmlemail (string subject, String sendhtml,String Receiveuser) {try {//sender//internetaddress from = new InternetAddress (Sender_userna            ME); The following is the set sender of nick name internetaddress from = new InternetAddress (Mimeutility.encodeword ("phantom") + "<" +sender_            Username+ ">");                        Message.setfrom (from);            Recipient InternetAddress to = new InternetAddress (receiveuser); Message.setrecipient (Message.RecipientType.TO, to);//can also have CC, BCC//Mail subject Message.setsubje                        CT (subject);            String content = sendhtml.tostring ();                        Message content, can also make plain text "Text/plain" message.setcontent (Content, "text/html;charset=utf-8");                        Save Message Message.savechanges ();            Transport = Session.gettransport ("SMTP");            SMTP authentication is the email user name password Transport.connect (mailHost, Sender_username, Sender_password) you use to send the email; Send Transport. SendMessage (Message, message.getallrecipients ());        System.out.println ("Send success!");        } catch (Exception e) {e.printstacktrace ();                }finally {if (transport!=null) {try {transport.close ();                } catch (Messagingexception e) {e.printstacktrace ();        }}}} public static void Main (string[] args) {JavaMail se = new JavaMail (false);    Se.dosendhtmlemail ("Mail Subject", "Mail Content", "[email protected]"); }}

Only the text can be sent above, if we want to send an attachment, we need to use the multipart object.

Import Java.io.File;
Import java.io.IOException;
Import Java.io.InputStream;
Import java.util.Properties;

Import Javax.activation.DataHandler;
Import Javax.activation.DataSource;
Import Javax.activation.FileDataSource;
Import Javax.mail.BodyPart;
Import Javax.mail.Message;
Import javax.mail.MessagingException;
Import Javax.mail.Multipart;
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;

public class Javamailwithattachment {
Private MimeMessage message;
Private session session;
Private Transport Transport;

Private String MailHost = "";
Private String Sender_username = "";
Private String Sender_password = "";

Private Properties Properties = new properties ();

/*
* Initialization method
*/
Public Javamailwithattachment (Boolean debug) {
InputStream in = JavaMailWithAttachment.class.getResourceAsStream ("mailserver.properties");
try {
Properties.load (in);
This.mailhost = Properties.getproperty ("Mail.smtp.host");
This.sender_username = Properties.getproperty ("Mail.sender.username");
This.sender_password = Properties.getproperty ("Mail.sender.password");
} catch (IOException e) {
E.printstacktrace ();
}

Session = Session.getinstance (properties);
Session.setdebug (debug);//debug information after opening
message = new MimeMessage (session);
}

/**
* Send mail
*
* @param subject
* Email Subject
* @param sendhtml
* Email Content
* @param receiveuser
* Recipient Address
* @param attachment
* Accessories
*/
public void Dosendhtmlemail (string subject, String sendhtml, String receiveuser, File attachment) {
try {
Sender
InternetAddress from = new InternetAddress (sender_username);
Message.setfrom (from);

Recipient
InternetAddress to = new InternetAddress (receiveuser);
Message.setrecipient (Message.RecipientType.TO, to);

Message subject
Message.setsubject (subject);

Add various parts of the message to the multipart object, including text content and attachments
Multipart Multipart = new Mimemultipart ();

Add Message body
BodyPart Contentpart = new MimeBodyPart ();
Contentpart.setcontent (sendhtml, "text/html;charset=utf-8");
Multipart.addbodypart (Contentpart);

Add the contents of an attachment
if (attachment! = NULL) {
BodyPart Attachmentbodypart = new MimeBodyPart ();
DataSource Source = new Filedatasource (attachment);
Attachmentbodypart.setdatahandler (new DataHandler (source));

Online spread of the solution file name garbled method, in fact, with Mimeutility.encodeword can be very convenient to fix
It is important to use the following BASE64 encoded conversion to ensure that your Chinese attachment header name is not garbled when it is sent
Sun.misc.BASE64Encoder enc = new Sun.misc.BASE64Encoder ();
Messagebodypart.setfilename ("=? GBK? B? "+ Enc.encode (Attachment.getname (). GetBytes ()) +"? = ");

Mimeutility.encodeword can avoid garbled file names
Attachmentbodypart.setfilename (Mimeutility.encodeword (Attachment.getname ()));
Multipart.addbodypart (Attachmentbodypart);
}

Place the multipart object in the message
Message.setcontent (multipart);
Save Message
Message.savechanges ();

Transport = Session.gettransport ("SMTP");
SMTP authentication is the email user name password you use to send mail
Transport.connect (MailHost, Sender_username, Sender_password);
Send
Transport.sendmessage (Message, message.getallrecipients ());

System.out.println ("Send success!");
} catch (Exception e) {
E.printstacktrace ();
} finally {
if (transport! = null) {
try {
Transport.close ();
} catch (Messagingexception e) {
E.printstacktrace ();
}
}
}
}

public static void Main (string[] args) {
Javamailwithattachment se = new javamailwithattachment (true);
File affix = new file ("c:\\ test-test.txt");
Se.dosendhtmlemail ("Mail Subject", "Mail Content", "[email protected]", affix);//
}
}

With accessories


Import Java.io.file;import java.io.ioexception;import Java.io.inputstream;import Java.util.properties;import Javax.activation.datahandler;import Javax.activation.datasource;import Javax.activation.filedatasource;import Javax.mail.bodypart;import Javax.mail.message;import Javax.mail.messagingexception;import Javax.mail.Multipart; 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;public class Javamailwithattachment {private MimeMessage message;    Private session session;    Private Transport Transport;    Private String MailHost = "";    Private String Sender_username = "";    Private String Sender_password = "";    Private Properties Properties = new properties (); /* * Initialization method */Public Javamailwithattachment (Boolean debug) {InputStream in = JavamailwithattachmEnt.class.getResourceAsStream ("Mailserver.properties");            try {properties.load (in);            This.mailhost = Properties.getproperty ("Mail.smtp.host");            This.sender_username = Properties.getproperty ("Mail.sender.username");        This.sender_password = Properties.getproperty ("Mail.sender.password");        } catch (IOException e) {e.printstacktrace ();        } session = Session.getinstance (properties);    Session.setdebug (debug);//debug message after open message = new MimeMessage (session); /** * Send mail * * @param subject * Email subject * @param sendhtml * Email content * @p Aram Receiveuser * Recipient address * @param attachment * ANNEX */public void Dosendhtmlemail ( String subject, String sendhtml, String receiveuser, File attachment) {try {//Sender Internet            Address from = new InternetAddress (sender_username); Message.setfrom (from);           Recipient InternetAddress to = new InternetAddress (receiveuser);            Message.setrecipient (Message.RecipientType.TO, to);            Mail subject Message.setsubject (subject);                        Add various parts of the message to the Multipart object, including text content and attachments Multipart Multipart = new Mimemultipart ();            Add message body bodypart Contentpart = new MimeBodyPart ();            Contentpart.setcontent (sendhtml, "text/html;charset=utf-8");                        Multipart.addbodypart (Contentpart);                Add the contents of the attachment if (attachment! = null) {BodyPart Attachmentbodypart = new MimeBodyPart ();                DataSource Source = new Filedatasource (attachment);                                Attachmentbodypart.setdatahandler (new DataHandler (source));                Online spread of the solution file name garbled method, in fact, with Mimeutility.encodeword can be very convenient to fix//here is very important, through the following BASE64 encoding conversion can ensure that your Chinese attachment header name in the send will not become garbled Sun.misc.BASE64Encoder enc = new Sun.misc.                Base64encoder (); Messagebodypart.setfilename ("=? GBK?                                B? "+ Enc.encode (Attachment.getname (). GetBytes ()) +"? = "); Mimeutility.encodeword can avoid garbled file names Attachmentbodypart.setfilename (Mimeutility.encodeword (Attachment.getname (                )));            Multipart.addbodypart (Attachmentbodypart);            }//Place the multipart object in message message.setcontent (multipart);            Save Message Message.savechanges ();            Transport = Session.gettransport ("SMTP");            SMTP authentication is the email user name password Transport.connect (mailHost, Sender_username, Sender_password) you use to send the email;            Send transport.sendmessage (message, message.getallrecipients ());        System.out.println ("Send success!");        } catch (Exception e) {e.printstacktrace ();                } finally {if (transport! = null) {try {transport.close (); } CatCH (messagingexception e) {e.printstacktrace (); }}}} public static void Main (string[] args) {javamailwithattachment se = new JAVAMAILWI        Thattachment (TRUE);        File affix = new file ("c:\\ test-test.txt"); Se.dosendhtmlemail ("Mail Subject", "Mail Content", "[email protected]", affix);/}}

Java Send mail

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.