Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ SendMail version of Java implementation with attachments     - Ubuntu install Liferea news subscription software (Linux)

- RedHat / CentOS ext4 partition can not be formatted large supplementary ext4 formatting (Linux)

- Automatic and Manual Proxy Settings Switch GNOME Shell Extension Proxy Switcher Recommend (Linux)

- To install PXE + Kickstart under CentOS 6.x operating system (Linux)

- Linux Oracle delete archived logs (Database)

- Via Twitter how open source library to be used anywhere Emoji emoticons (Linux)

- Docker deployment practices in Ubuntu (Server)

- How to remove the files inside the privacy of data on Linux (Linux)

- WebLogic 12c Configuration Node Manager Managed Server (Database)

- Win8 mount disk partitions under Ubuntu (Linux)

- RocketMQ Message Queuing simple deployment (Linux)

- PostgreSQL use pgpool achieve high availability (Database)

- Mhddfs: multiple smaller partitions into one large virtual storage (Linux)

- Java Cookie Comments (Programming)

- Install Ruby on Rails in Ubuntu 15.04 in (Linux)

- JavaScript property of checkbox.disabled (Programming)

- Configuring Android NDK development environment for Mac OS X (Linux)

- Story timestamp and time zones: daily programmer (Programming)

- Add your own kernel and ramfs based on an existing Linux LiveCD (Linux)

- CentOS 7 How to install MySQL Server (Database)

 
         
  SendMail version of Java implementation with attachments
     
  Add Date : 2017-05-10      
         
       
         
  Before his side there is a sendmail component, but can only realize sending text today visiting the blog, accidentally discovered a function to achieve senfmail send attachments to achieve the java, so he tested and implemented can be tested successful implementation of attachments, want to send Bo collection by the way, also appeared in the middle of the issues and to share with everyone:

1. First, create a new folder in the Mail lib project, import javax.mail.jar package;

2. Create a new project in the Mail conf folder, create a new file: mail-info.properties, configure;

mail.host = smtp.abc.com
mail.port = 25
mail.username=abc@abc.com
mail.password = ******
mail.from=abc@abc.com
mail.to=root@abc.com
3. Create a util the package, put inside reads the configuration file and save temporary AppContext.java profile SystemContains.java;

package util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/ **
 * Reads the configuration file
 * December 31, 2014
* /
public enum AppContext {

INSTANCE;

public Properties configuration = new Properties ();

public void init () {

InputStream is = this.getClass () getResourceAsStream ( "/ mail-info.properties").;
 if (is! = null) {
 try {
this.configuration.clear ();
this.configuration.load (is);
 } Catch (IOException e) {
 } Finally {
 try {
is.close ();
 } Catch (Throwable t) {}
}
}

}

public String getConfigValue (String key) {

 return this.configuration.getProperty (key);

}

}
 
package util;
/ **
 * Temporary save profile information
* /
public class SystemConstants {

// Info

public static final String MAILHOST = AppContext.INSTANCE.getConfigValue ( "mail.host");

public static final String MAILPORT = AppContext.INSTANCE.getConfigValue ( "mail.port");

public static final String MAILUSERNAME = AppContext.INSTANCE.getConfigValue ( "mail.username");

public static final String MAILPASSWORD = AppContext.INSTANCE.getConfigValue ( "mail.password");

public static final String MAILFROM = AppContext.INSTANCE.getConfigValue ( "mail.from");

public static final String MAILTO = AppContext.INSTANCE.getConfigValue ( "mail.to");
}
 4. Send the new class file compression and decompression JavaMail.java class ZIP.java in mail package;

package mail;

import java.io.File;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
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;

import util.AppContext;
import util.SystemConstants;
/ **
 * Send email
 * December 31, 2014
* /

public class JavaMail {
/ **
 * Message object will be stored our actual e-mail message sent,
 * Message object is used as a MimeMessage object to create and need to know which one should be selected JavaMail session.
* /
 private MimeMessage message;

/ **
 * Session class represents a mail session in the JavaMail.
 * Every JavaMail-based applications at least one Session (can have any number of Session).
*
 * JavaMail Properties need to create a session object.
 * Find "mail.smtp.host" attribute value is the host to deliver mail
 * Find "mail.smtp.auth" authentication is currently free mail servers need this one
* /
 private Session session;

/ ***
 * Mail can be sent either is to be is received. JavaMail use two different classes to complete these two functions: Transport and Store.
 * Transport is used to send information, and Store for receivers. For this tutorial we only need to use Transport object.
* /
 private Transport transport;

/ *
 * Initialization method
* /
 public JavaMail (boolean debug) {
 session = Session.getInstance (AppContext.INSTANCE.configuration);
session.setDebug (debug); // open after debugging information
 message = new MimeMessage (session);
}

/ **
 * send email
 * @param Subject message subject
 * @param SendHtml message content
* /
 public void sendEmail (String subject, String sendHtml) {
 try {
 // Sender
 // InternetAddress from = new InternetAddress (sender_username);
 // The following is to set the sender's Nick name
 InternetAddress from = new InternetAddress (MimeUtility.encodeWord ( "zhanglincc") + "< " + SystemConstants.MAILUSERNAME + ">");
message.setFrom (from);

 // Recipient
 InternetAddress to = new InternetAddress (SystemConstants.MAILTO);
 message.setRecipient (Message.RecipientType.TO, to); // may also be CC, BCC

 // Email Subject
message.setSubject (subject);

 String content = sendHtml.toString ();

 // Message content, you can also make plain text "text / plain"
 message.setContent (content, "text / html; charset = UTF-8");

 // Save messages
message.saveChanges ();

 // Smtp authentication, that you use to send e-mail e-mail username and password
 transport = session.getTransport ( "smtp");
 transport.connect (SystemConstants.MAILHOST, SystemConstants.MAILUSERNAME, SystemConstants.MAILPASSWORD);

 // 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 ();
}
}
}
}

/ **
 * send email
 * @param Subject message subject
 * @param SendHtml message content
 * @param Attachment Accessories
* /
 public void sendEmail (String subject, String sendHtml, String filePath) {

File file = new File (filePath);

if (file.exists ()) {

 try {

 // Sender

 InternetAddress from = new InternetAddress (SystemConstants.MAILUSERNAME);

message.setFrom (from);

 String [] strings = SystemConstants.MAILTO.split ( ";");

 Address [] receiverAddress = new Address [strings.length];

 for (int i = 0; i < strings.length; i ++) {

receiverAddress [i] = new InternetAddress (strings [i]);

}

 message.setRecipients (Message.RecipientType.TO, receiverAddress);

 // Email Subject

message.setSubject (subject);

 // Add the contents of the message to various parts of the multipart objects, including text and attachments

 Multipart multipart = new MimeMultipart ();

 // Add message body

 BodyPart contentPart = new MimeBodyPart ();

 contentPart.setContent (sendHtml, "text / html; charset = UTF-8");

multipart.addBodyPart (contentPart);

// If the given path is a directory on the compression

if (file.isDirectory ()) {

File fileTemp = new File (. File.getParentFile () getAbsoluteFile () + "\" + file.getName () + ". Zip");

System.out.println (fileTemp.getAbsolutePath ());

ZIP.zipFiles (file.listFiles (), fileTemp);

file = fileTemp;

System.out.println (file.isFile ());

}

 // Add the contents of the annex

 if (file.isFile ()) {

 BodyPart attachmentBodyPart = new MimeBodyPart ();

 DataSource source = new FileDataSource (file);

 attachmentBodyPart.setDataHandler (new DataHandler (source));

 // Method to solve the file name garbled circulated on the Internet, in fact, with MimeUtility.encodeWord can easily get

 // Here is very important, by the following Base64 encoding conversion may ensure that your Chinese name when sending attachments title does not become garbled

 //sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder ();

 //messageBodyPart.setFileName("=?GBK?B?"+ enc.encode (attachment.getName () getBytes ().) +) "=?";

//MimeUtility.encodeWord Avoid file name garbled

attachmentBodyPart.setFileName (MimeUtility.encodeWord (file.getName ()));

multipart.addBodyPart (attachmentBodyPart);

}

 // The multipart objects into the message

message.setContent (multipart);

 // Save messages

message.saveChanges ();

 transport = session.getTransport ( "smtp");

 // Smtp authentication, that you use to send e-mail e-mail username and password

 transport.connect (SystemConstants.MAILHOST, SystemConstants.MAILUSERNAME, SystemConstants.MAILPASSWORD);

 // 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 ();

}

}

}

} Else {

System.out.println ( "Annex wrong address");


System.exit (-1);

}
}

}
 
package mail;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/ **
 * Compressed file, extract the compressed file
 * December 31, 2014
* /
public class ZIP {


/ **

 * Function: compress multiple files into a zip file

 * @param Srcfile: source file list

 Compressed files: * @param zipfile

* /

public static void zipFiles (File [] srcfile, File zipfile) {

byte [] buf = new byte [1024];

try {

// ZipOutputStream categories: compressed files or complete folders

ZipOutputStream out = new ZipOutputStream (new FileOutputStream (zipfile));

for (int i = 0; i < srcfile.length; i ++) {

FileInputStream in = new FileInputStream (srcfile [i]);

out.putNextEntry (new ZipEntry (srcfile [i] .getName ()));

int len;

while ((len = in.read (buf))> 0) {

out.write (buf, 0, len);

}

out.closeEntry ();

in.close ();

}

out.close ();

System.out.println ( "compression completed.");

} Catch (Exception e) {

e.printStackTrace ();

}

}

/ **

 * Function: Extract

 * @param Zipfile: unzip files

 * @param DescDir: decompressed target directory

 * @throws IOException

* /

@SuppressWarnings ( "Rawtypes")

public static void unZipFiles (File zipfile, String descDir) {

File file = new File (descDir);

if (! file.exists ()) {

try {

file.mkdir ();

} Catch (Exception e) {

e.printStackTrace ();

}

}

try {

ZipFile zf = new ZipFile (zipfile);

for (Enumeration entries = zf.entries (); entries.hasMoreElements ();) {

ZipEntry entry = (ZipEntry) entries.nextElement ();

String zipEntryName = entry.getName ();

InputStream in = zf.getInputStream (entry);

OutputStream out = new FileOutputStream (descDir + zipEntryName);

byte [] buf1 = new byte [1024];

int len;

while ((len = in.read (buf1))> 0) {

out.write (buf1, 0, len);

}

in.close ();

out.close ();

System.out.println ( "unzip completed.");

}

zf.close ();

} Catch (Exception e) {

e.printStackTrace ();

}

}

public static void main (String [] args) {

// Need to decompress the file

File file = new File ( "D: \ test");

File filenew = new File ( "D: \ test.zip");

zipFiles (file.listFiles (), filenew);

// Destination directory after extracting

String dir = "D: \ workspace \";

unZipFiles (filenew, dir);

}
}
 5. Create a new test class for testing;

package main;

import util.AppContext;
import mail.JavaMail;

public class Main {
 public static void main (String [] args) {

AppContext.INSTANCE.init ();

JavaMail mail = new JavaMail (false);
 mail.sendEmail ( "from lynnzhangcc mail", "I am the message content");
 mail.sendEmail ( "test accessories for the mailing theme folder" and "test accessories for the message contents of a folder", "D: \ test");
 mail.sendEmail ( "test file attachment to the message subject," "test the contents of the message attachment file", "D: \ test");
}
}
 
If normal operation, console will print send success! Statements.

During operation may appear following exception:

1.java and run the compiled version of the conflict

 The exception indicates that compile and run java jdk version, you may be abnormal project location change occurs, the solution is as follows:

Right-click on the project Mail, select properties

 This problem can be solved.

2. Authentication exception;

The problem is usually not authenticated by, just mail-info.properties configuration, do not use the application time is not long mailboxes can be resolved.
     
         
       
         
  More:      
 
- DRBD Principle and Features Overview (Server)
- VMware virtual machine Ubuntu install arm-linux-gcc cross-compiler environment (Linux)
- Install and use automated tools Ansible in CentOS 7 (Linux)
- Fedora 23 How to install LAMP server (Server)
- Oracle Automatic Diagnostic Repository (Automatic Diagnostic Repository, ADR) (Database)
- GoldenGate for Oracle data consistency initializing (Database)
- Live Wallpaper for Linux release adds dynamic background (Linux)
- Linux security settings Notes (Linux)
- Linux systems for entry-learning - Install Go language in Linux (Linux)
- C ++ How to determine the types of constants (Programming)
- Three easy open source firewall on the Linux platform (Linux)
- Java threads and thread pools (Programming)
- mysqldump implement database logical backup (Database)
- How to install Git on CentOS 7 (Linux)
- 5 steps to help you become a good Docker contributors (Linux)
- PHP interview questions of design patterns (Programming)
- Github with .gitignore ignore specified file (Linux)
- impdp error ORA-39001, ORA-39000, ORA-31619 (Database)
- MySQL 5.6.12 binary log path switching binlog (Database)
- Use mod_wsgi Django application deployment (Server)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.