Implementation of Java mail delivery _java

Source: Internet
Author: User
Tags mailmessage

The mail is in the daily life, this article mainly introduced the Java implementation based on SMTP to send the mail the method, the example has analyzed the Java to send the mail based on the SMTP service the related skill, has certain reference value, the need friend may refer under.

1. Write a Mailsendproper class encapsulation of the required attributes

Import java.util.Properties;          public class Mailsendproper {private String Host;          The IP private String Port of the outgoing mail server;      The port number of the sending mail server is private String sendaddress;     The address of the sender of the message is private String receiveaddress;        The address of the mail recipient is private String username;        Log in to send the user name of the mailbox private String password;   Login to send the password private Boolean isvalidate = true;        Whether to require authentication private String subject;       Message headers private String content;
    Message content public String Getsubject () {return subject;
    } public void Setsubject (String subject) {this.subject = subject;
    Public String getcontent () {return content;
    public void SetContent (String content) {this.content = content;
    Public String GetHost () {return Host;
    The public void Sethost (String host) {host = host;
    Public String Getport () {return Port; public void Setport (String port) {PoRT = Port;
    Public String getsendaddress () {return sendaddress;
    } public void Setsendaddress (String sendaddress) {sendaddress = sendaddress;
    Public String getreceiveaddress () {return receiveaddress;
    } public void Setreceiveaddress (String receiveaddress) {receiveaddress = receiveaddress;
    Public String GetUserName () {return username;
    } public void Setusername (String username) {this.username = username;
    Public String GetPassword () {return password;  
    } public void SetPassword (String password) {this.password = password;
    public Boolean isisvalidate () {return isvalidate;
    } public void Setisvalidate (Boolean isvalidate) {this.isvalidate = isvalidate;
      Public Properties GetProperties () {Properties Properties = new properties (); Properties.put ("Mail.smtp.host", this.
      Host); Properties.put ("Mail.smtp.port", this.Port); Properties.put ("Mail.smtp.auth", isvalidate?)
      True ": false");
    return properties;

 }
}

2, write a emailmessage package to send information

public class Emailmessage {
private String title;
Private String context;
Private String Toemail;

Public Emailmessage () {
super ();
Public
Emailmessage (string title, string context, String toemail) {
super ();
this.title = title;
This.context = context;
This.toemail = Toemail;
Public
String GetTitle () {return
title;
Public
void Settitle (String title) {
this.title = title;
Public
String GetContext () {return context
;
Public
void SetContext (String context) {
This.context = context;
Public
String Gettoemail () {return
toemail;
} public
void Settoemail (String toemail) {
this.toemail = Toemail;
}
}

3, write a Mailattorney mailbox password validator class

Import Javax.mail.Authenticator;
Import javax.mail.PasswordAuthentication;

public class Mailattorney extends authenticator {
private String username;
private String password;

Public Mailattorney (String username,string password) {
this.username = Username;
This.password = password;
//Overwrite parent class method, get Password authenticator
@Override
protected passwordauthentication getpasswordauthentication () {
R  Eturn new Passwordauthentication (Username,password);
}
}

4, write a MailSend mail tool class

Import Java.util.Date;
Import javax.mail.Address;
Import Javax.mail.Message;
Import javax.mail.Session;
Import Javax.mail.Transport;
Import javax.mail.internet.InternetAddress;

Import Javax.mail.internet.MimeMessage; Import com.

VTBBS.entity.EmailMessage; public class MailSend {public static Boolean mailtest (Mailsendproper mailsender) {Mailattorney attorney = nul
        L if (Mailsender.isisvalidate ()) {//To determine whether the need for identity authentication attorney = new Mailattorney (Mailsender.getusername (), MAILSENDER.GETPA
        ssWOrd ()); ////based on the mailbox session properties and the password validator constructs a mailbox-sending seesion sessions = Session.getinstance (Mailsender.getproperties (), Attorn
        EY);
        Create a mail message based on session MailMessage = new MimeMessage (session);
          try {//Create the address of the mail sender from = new InternetAddress (mailsender.getsendaddress ());
          Set the sender of the mailbox Message Mailmessage.setfrom (from); Create the address that the message receives here, and set it to the message in mail to = new InternetAddress (maiLsender.getreceiveaddress ());
          Mailmessage.setrecipient (Message.RecipientType.TO, to); Mailmessage.setsubject (Mailsender.getsubject ()); Set the message header mailmessage.setsentdate (new Date ()); Set the time to send mail Mailmessage.settext (mailsender.getcontent ());
          Set the content of the message transport.send (MailMessage);
        return true;
          catch (Exception e) {e.printstacktrace ();
        return false;
        } public static Boolean SendEmail (Emailmessage message) {Mailsendproper mail = new Mailsendproper ();          Mail.sethost ("smtp.126.com");
        SMTP Simple Mail Transfer Protocol, the default port number is Mail.setport ("25");              Mail.setisvalidate (TRUE);               Need AH authentication Mail.setusername ("");               Set login username Mail.setpassword ("");             Set the sender's password mail.setsendaddress ("");  Set the address of the sender to send this and the login username is the same mail.setreceiveaddress (Message.gettoemail ()); Set the address of the recipient Mail.setsubject (MESSage.gettitle ());      Set Mailbox title Mail.setcontent (Message.getcontext ());
    Set the contents of the Mailbox Return mailtest (mail);

 }

}

Note: Use of the mailbox must be opened POP3/SMTP service to send a successful, different mailboxes, mailbox transmission protocol is not the same as:

QQ mailbox: SMTP transport protocol is smtp.qq.com port 25

POP3 transport protocol is pop3.qq.com Port 110

5, the use of method testing

public static void Main (string[] args) {
emailmessage message = new Emailmessage ();
String code = string.valueof (Math.random ()). SUBSTRING (3, 9);                  Generate Authenticode
message.settitle ("Mailbox Verification"); Mail title
message.setcontext ("Dear User Hello, your verification code is" +code+ ".) "); Message content
Message.settoemail ("940202884@qq.com");//Who to send to
System.out.println (mailsend.sendemail)? Send Success ": Send Failed");
}

I hope this article will help you learn Java programming.

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.