Java Send mail, encounter the wonderful problem

Source: Internet
Author: User

    • Environment Introduction

Online Environment: java Version "1.7.0_79"

Development environment: java Version "1.8.0_144"

Development tools: Idea

    • Writing code

External Jar:activation.jar required by the program | | | | | Mail.jar

Java code:

 PackageCOM.DSP;ImportJavax.activation.DataHandler;ImportJavax.activation.DataSource;ImportJavax.activation.FileDataSource;ImportJavax.mail.*;Importjavax.mail.internet.*;ImportJava.io.BufferedInputStream;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.InputStream;Importjava.util.Properties;/** *@authorWangyuxiang * @Description * @Date 2018/2/2 a.m. 11:37 **/ Public classSendMail { Public Static voidMain (string[] args) {Try{String path= System.getproperty ("User.dir") + "/mail.properties"; System.out.println (Path+""); Properties Properties=system.getproperties (); InputStream in=NewBufferedinputstream (NewFileInputStream (path));            Properties.load (in); FinalString Sender =NewString (Properties.getproperty ("Sender"). GetBytes ("Iso8859-1"), "UTF-8"); String Host= Properties.getproperty ("host"); String Recipients=NewString (Properties.getproperty ("Recipients"). GetBytes ("Iso8859-1"), "UTF-8"); FinalString Senderpassword =NewString (Properties.getproperty ("Senderpassword"). GetBytes ("Iso8859-1"), "UTF-8"); String title=NewString (Properties.getproperty ("title"). GetBytes ("Iso8859-1"), "UTF-8"); String text=NewString (Properties.getproperty ("text"). GetBytes ("Iso8859-1"), "UTF-8"); String Filedir=NewString (Properties.getproperty ("Filedir"). GetBytes ("Iso8859-1"), "UTF-8"); //setting up a mail serverProperties.setproperty ("Mail.smtp.host", host); Properties.put ("Mail.smtp.auth", "true"); Authenticator Authenticator=NewAuthenticator () {@Overrideprotectedpasswordauthentication getpasswordauthentication () {return Newpasswordauthentication (Sender, Senderpassword);            }            }; //Gets the default Session object. Session session =Session.getdefaultinstance (properties, authenticator); MimeMessage message=NewMimeMessage (session); System.out.println (Title+text); Message.setfrom (Newinternetaddress (Sender)); Message.addrecipient (Message.RecipientType.TO,Newinternetaddress (Recipients)); Message.setsubject (title,"UTF-8"); Multipart Multipart=NewMimemultipart (); /*set text message part*/bodypart Messagebodypart=NewMimeBodyPart (); Messagebodypart.setcontent (text,"Text/html;charset=utf-8");            Messagebodypart.settext (text);            Multipart.addbodypart (Messagebodypart); /*Accessories Section*/File File=NewFile (Filedir); File[] FileList=File.listfiles ();  for(File fl:filelist) {if(Fl.isfile ()) {//AccessoriesMessagebodypart =NewMimeBodyPart (); DataSource Source=NewFiledatasource (FL); Messagebodypart.setdatahandler (NewDataHandler (source));                    Messagebodypart.setfilename (Mimeutility.encodeword (Fl.getname ()));                Multipart.addbodypart (Messagebodypart); }            }            //Send Full Messagemessage.setcontent (multipart); //Send Messagetransport.send (message); System.out.println ("Sent message successfully ..."); } Catch(Exception Mex) {mex.printstacktrace (); }    }}
Sendmail.java

Properties File:

1 #发件人电子邮箱 & password 2 sender=***@126. com  3 senderpassword=****** 4  #发送邮件的主机 5 host=smtp.126. com  6  7#收件人电子邮箱 8 recipients=***@qq. com  9 title= mail header  one by one text=  e-mail content  filedir= The absolute directory in which attachments are sent (all files in the directory, except folders, are sent as attachments)
mail.properties

 

  • Package A well-written program as a jar file
    • The first time you hit the jar (the code, with the referenced external jar, hits a jar <<< external jar is to extract the code in the external jar into the final jar >>>)
      •  
      • Run locally through
      • Server Run Error
        Exception in thread "main" Java.lang.SecurityException:no manifiest sections for signature file entry Javax/activation/mim Etype.class at Sun.security.util.SignatureFileVerifier.verifySection (signaturefileverifier.java:446) at Sun.security.util.SignatureFileVerifier.processImpl (signaturefileverifier.java:297) at Sun.security.util.SignatureFileVerifier.process (signaturefileverifier.java:240) at Java.util.jar.JarVerifier.processEntry (jarverifier.java:317) at Java.util.jar.JarVerifier.update ( jarverifier.java:228) at Java.util.jar.JarFile.initializeVerifier (jarfile.java:348) at Java.util.jar.JarFile.getInputStream (jarfile.java:415) at Sun.misc.urlclasspath$jarloader$2.getinputstream ( urlclasspath.java:775) at Sun.misc.Resource.cachedInputStream (resource.java:77) at Sun.misc.Resource.getByteBuffer (resource.java:160) at Java.net.URLClassLoader.defineClass (urlclassloader.java:436) at JAVA.NET.URLCLASSLOADER.ACCESS$100 (urlclassloader.java:71) at Java.net.urlclassloader$1.run (URLClassLoader.java:361) at Java.net.urlclassloader$1.run (urlclassloader.java:355) at java.security.AccessController.doPrivileged ( Native Method) at Java.net.URLClassLoader.findClass (urlclassloader.java:354) at Java.lang.ClassLoader.loadClass ( classloader.java:425) at Sun.misc.launcher$appclassloader.loadclass (launcher.java:308) at Java.lang.ClassLoader.loadClass (classloader.java:358) at Sun.launcher.LauncherHelper.checkAndLoadMain ( launcherhelper.java:482)
        ERR
      • Error reason Mail.jar has Sun's signature, you do not have your signature after the work, security Manager prohibits you to use

    • The second time to hit the jar bag
      • Separating your own code from the external jar package specify the relative path of the external jar in the MANIFEST.MF file
      • Local run pass, service error
      •  exception in Thread "main" java.lang.unsupportedclassversionerror:com/dsp/ sendmail:unsupported Major.minor version 52.0 at Java.lang.ClassLoader.defineClass1 (Native Method) at Java.lang.ClassLoader.defineClass (classloader.java:800) at Java.security.SecureClassLoader.defineClass ( secureclassloader.java:142) at Java.net.URLClassLoader.defineClass (urlclassloader.java:449) at JAVA.NET.URLCLASSLOADER.ACCESS$100 (urlclassloader.java:71) at Java.net.urlclassloader$1.run (URLClassLoader.java : 361) at Java.net.urlclassloader$1.run (urlclassloader.java:355) at java.security.AccessController.doPrivileged ( Native Method) at Java.net.URLClassLoader.findClass (urlclassloader.java:354) at Java.lang.ClassLoader.loadClass ( classloader.java:425) at Sun.misc.launcher$appclassloader.loadclass (launcher.java:308) at Java.lang.ClassLoader.loadClass (classloader.java:358) at Sun.launcher.LauncherHelper.checkAndLoadMain ( launcherhelper.java:482)  
        ERR

        Error Reason: JDK version and class version are inconsistent, usually JDK version is too low

      • workaround : Modify idea Language level: solve the development environment 1.8 JDK is higher than the online 1.7 jdk, IntelliJ idea is also supported, the new version will generally be backwards compatible with the old version of the features
      • Because the server JDK version is low: so the following:

The reason that you write your own code to separate a jar: Avoid the update, the code after the upload program is too large (if all the external jar is hit in a jar file, the space is very large, wasting resources)

Run jar

Place the external jar under LIB, place the jar where the main function resides in the Lib sibling directory, and put the property file in the directory running the jar (because the directory I get in the code is the directory where the jar file is run)

Successful execution

[Email protected] email]# Java-jar Sendmail.jar

/usr/local/email/mail.properties

e-mail title just waiting for you. Message the dog doesn't talk

Sent message successfully ....

[Email protected] email]#

Java Send mail, encounter the wonderful problem

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.