JavaMail Send mail directly

Source: Internet
Author: User
Tags mail exchange mx record

Generally use JavaMail to send mail will need to log on to the external SMTP server (such as smtp.163.com) two times forwarding, in fact, as long as the domain name of the mail Exchange Server address (MX) can be sent directly to the mail

The Dnsjava (: http://www.dnsjava.org/) is used here to get the MX record. Considering the efficiency issue, you can save each acquired MX record to an XML or database, the next use is to retrieve the local data first, and then get its MX record if it does not exist.

Sendmail.java

Import org.xbill.dns.*;
Import java.util.Properties;
Import javax.mail.internet.*;
Import javax.mail.*;
Import javax.mail.Address;
Import Javax.mail.Message;
Import javax.activation.*;

public class SendMail
... {
/** *//**
* @param mailfrom sender, any value
* @param mailTo recipient Address
* @param subject Theme
* @param content
* @param filepath Accessories
* @return is sent successfully
*/
public static Boolean send (String Mailfrom, String mailTo, string subject, string content,
String[] filepath)
... {
if (!mailto.matches ("\w+" ([-_.] \w+) *@\w+ ([-.] \w+) *\.\w+ ([-.] \w+)) ... {//Judging format
return false;
}
Try ... {
String hostName = Mailto.split ("@") [1];
String host = null;

            Lookup lookup = new Lookup (hostName, type.mx);  //Get the MX record for the host
            Lookup.run ();
            if (Lookup.getresult ()! = lookup.successful) ... {
                return false;
           }
            Else ... {
                record[] result = Lookup.getanswers ();
                host = result[0]. Getadditionalname (). toString (); Only the first server
           }

is taken here

            Properties Prop = new properties ();
            prop.put ("Mail.smtp.host", host);

            Session ssn = session.getinstance (prop, NULL) ;
           //ssn.setdebug (true);
           //system.setout (New PrintStream ("New File") Sendlog.log ")));
            Address addressfrom = new InternetAddress ( Mailfrom, "Sender");
            Address addressto = new InternetAddress ( MailTo, "Receiver");
            
             MimeBodyPart Messagebodypart = new MimeBodyPart ();
            Multipart Multipart = new Mimemultipart ();

Messagebodypart.settext (content);
Messagebodypart.setheader ("Content-type", "text/html");
Multipart.addbodypart (Messagebodypart);
DataSource Source = null;

if (filepath! = null) ... {//Add attachments
for (int i = 0; i < filepath.length; i++) ... {
Messagebodypart = new MimeBodyPart ();
Source = new Filedatasource (Filepath[i]);
Messagebodypart.setdatahandler (new DataHandler (source));
Messagebodypart.setfilename (Filepath[i]);
Multipart.addbodypart (Messagebodypart);
}
}

MimeMessage message = new MimeMessage (SSN);

Message.setsubject (subject);
Message.setfrom (Addressfrom);
Message.addrecipient (Message.RecipientType.TO, Addressto);
Message.setcontent (multipart);
Message.savechanges ();

            Transport tran = (Transport) ssn.gettransport ("SMTP");
            tran.connect ();
            tran.sendmessage (message, Message.getallrecipients ());
            tran.close ();
            return true;
       } catch (Exception e) ... {
           //e.printstacktrace ();
            return false;
       }
   }
}
Test:

public class Test
... {
public static void Main (string[] args)
... {
Sendmail.send ("[email protected]", "[email protected]", "Hello", "hello", null);
}
}
Note: Some mail servers will verify the IP of the link that is currently submitting the message, that is, verify that the IP record for the yourdomain.suffix is the same as the current link, so if the sender address is filled out it may not be successful

JavaMail Send mail directly

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.