Example of sending an attachment with an attachment using Java _java

Source: Internet
Author: User
Tags mixed

Here is the use of JavaMail technology, the front desk used FCKeditor to do the message beautification, because just an example, the background is sent only to save the message in the local, but you can view, if you need to actually send, please refer to my other blog posts, I wrote a lot about the message sent sample!

In addition to referencing FCKeditor, JSP page pages should be aware that we need to send an attachment:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <%@ taglib prefix= "C" uri= "http://" 
Java.sun.com/jsp/jstl/core "%> <% String Path = Request.getcontextpath (); 
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  



To prevent garbled, it passes through a filter:

Package org.filter; 
Import java.io.IOException; 
Import Javax.servlet.Filter; 
Import Javax.servlet.FilterChain; 
Import Javax.servlet.FilterConfig; 
Import javax.servlet.ServletException; 
Import Javax.servlet.ServletRequest; 
Import Javax.servlet.ServletResponse; 
/** 
 * Filter to prevent garbled 
 * @ description 
 * @author Cuisuqiang 
 * @version 1.0 
 * @since * * Public 
Class Encodingfilter implements Filter {public 
  void Destroy () { 
  } public 
  void Dofilter (ServletRequest request , servletresponse response, 
      Filterchain chain) throws IOException, servletexception { 
    Request.setcharacterencoding ("UTF-8"); 
    Response.setcharacterencoding ("UTF-8"); 
    Chain.dofilter (request, response); 
  public void init (Filterconfig arg0) throws servletexception { 
  } 
} 


And then to the servlet processing attachments and information, here is no exception handling, error directly errors:

Package org.servlet; 
Import java.io.*; 
Import java.util.*; 
Import javax.servlet.ServletException; 
Import Javax.servlet.http.HttpServlet; 
Import Javax.servlet.http.HttpServletRequest; 
Import Javax.servlet.http.HttpServletResponse; 
Import Org.apache.commons.fileupload.FileItem; 
Import Org.apache.commons.fileupload.FileItemFactory; 
Import org.apache.commons.fileupload.FileUploadException; 
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory; 
Import Org.apache.commons.fileupload.servlet.ServletFileUpload; 
Import Org.entity.MailModel; 
Import Org.mail.SendMail; /** * Receive forms, process attachments, assemble mail objects, and invoke send interface * @ Description Create temporary file in C disk * @author Cuisuqiang * @version 1.0 * @since * * @SuppressWarni 
  NGS ("Serial") public class Sendmailservlet extends HttpServlet {@SuppressWarnings ({"Unchecked", "deprecation"}) @Override protected void Service (HttpServletRequest request, httpservletresponse response) throws Servletexcept Ion, IOException {//build disk Factory FILEITEMFActory factory = new Diskfileitemfactory (); 
    form field Servletfileupload upload = new Servletfileupload (factory); 
    list<fileitem> items = null; String bgimg = "1"; 
    The default is the first background picture try {items = upload.parserequest (request); 
    catch (Fileuploadexception e) {e.printstacktrace (); 
    } Mailmodel mail = new Mailmodel (); 
    InputStream is = null; 
          for (Fileitem item:items) {if (!item.isformfield ()) {//If attachment if (item.getsize () > 0) { 
          is = Item.getinputstream (); 
          String filename = ""; 
          if (Item.getname (). IndexOf ("\") = = = 1) {filename = "c:\\tmp\\" + item.getname (); 
          else {filename = "c:\\tmp\\" + item.getname (). substring (Item.getname (). LastIndexOf ("\)"); 
          } if (is.marksupported ()) {System.out.println ("No uploaded files or files have been deleted"); 
            else {File File = new file (filename); FileoutputstrEAM fos = new FileOutputStream (file); Set up output stream byte[] buffer = new byte[8192]; 
            8K bytes per read, large file upload no problem int count = 0; 
            while ((count = is.read (buffer)) > 0) {//loop write to Hard disk fos.write (buffer, 0, count); } fos.close (); 
            Turn off the input/output stream is.close (); 
            if (Item.getfieldname (). Equals ("Ufile")) {mail.setfilepath (filename); 
            else if (Item.getfieldname (). Equals ("Umusic")) {mail.setmusicpath (filename); else {//Process text information if (Item.getfieldname (). Equals ("title")) {mail.se 
        Ttitle (item.getstring ("UTF-8")); 
        else if (Item.getfieldname (). Equals ("content")) {Mail.setcontext (item.getstring ("UTF-8")); 
        else if (Item.getfieldname (). Equals ("to")) {Mail.setto (item.getstring ("UTF-8")); else if (Item.getfieldname (). Equals ("copy")) {Mail.setcOpy (item.getstring ("UTF-8")); 
        else if (Item.getfieldname (). Equals ("Bgimg")) {bgimg = item.getstring ("UTF-8"); 
    }} String Bgpath = Request.getrealpath ("/") + "\\IMAGES\\BG" + bgimg + ". jpg"; 
    Mail.setbgpath (Bgpath); 
    try {sendmail.sendmail (mail); 
    catch (Exception e) {e.printstacktrace (); 
  } response.sendredirect (Request.getcontextpath () + "/sendmail.jsp"); 
 } 
}



There is also no validation, the message is received after the assembly of a mail entity object, passed to the sending interface to send:
Entity, I don't write the Get and set methods:

Package org.entity; 
/** * 
 The object of a message * 
 @ description 
 * @author Cuisuqiang 
 * @version 1.0 
 * @since * * Public 
class Mailmodel { 
  /** 
   * PRIMARY KEY * * 
  private int id; 
 
  /** 
   * Message title * * 
  private String title; 
 
  /** 
   * Send to who 
  /private String to; 
 
  /** 
   * Background Image address * * 
  private String bgpath; 
 
  /** 
   * CC to WHO * * * 
  private String copy; 
 
  /** 
   * Message content * * 
  private String context; 
 
  /** 
   * Attachment address * * 
  private String filePath; 
  /** 
   * Background music address 
   * 
  /private String musicpath; 
} 



And then we'll look at the core processing classes:

Package org.mail; 
Import Java.io.File; 
Import Java.io.FileOutputStream; 
Import Java.io.OutputStream; 
Import Java.util.Date; 
Import java.util.Properties; 
Import Javax.activation.DataHandler; 
Import Javax.activation.DataSource; 
Import Javax.activation.FileDataSource; 
Import Javax.mail.Message; 
Import javax.mail.Session; 
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 Org.entity.MailModel; /** * Send a message * Note notice here is not actually sent but saved in the C disk temporary file, really send, please refer to my blog * @author Cuisuqiang * @version * * @since * * * * PU Blic class SendMail {public static void SendMail (Mailmodel mail) throws Exception {Properties props = new Proper 
    Ties (); 
    Props.put ("Mail.smtp.auth", "true"); 
    Session session = Session.getinstance (props); 
    Message message = new MimeMessage (session); InternetAddress from = newInternetAddress (); 
    From.setpersonal ("Mimeutility.encodetext in Wind <cuisuqiang@163.com>"); 
    Message.setfrom (from); 
    InternetAddress to = new InternetAddress (Mail.getto ()); 
    Message.setrecipient (Message.RecipientType.TO, to); CC if (null!= mail.getcopy () &&! "". 
      Equals (Mail.getcopy ())) {internetaddress copy = new internetaddress (Mail.getcopy ()); 
    Message.setrecipient (Message.RecipientType.CC, copy); 
    } message.setsubject (Mimeutility.encodetext (Mail.gettitle ())); 
    Message.setsentdate (New Date ()); 
    Specifies a mixed relationship mimemultipart Msgmultipart = new Mimemultipart ("mixed"); 
    Message.setcontent (Msgmultipart); 
    MimeBodyPart content = new MimeBodyPart (); 
    Msgmultipart.addbodypart (content); 
    Dependency relationship Mimemultipart Bodymultipart = new Mimemultipart ("related"); 
    Content.setcontent (Bodymultipart); 
    MimeBodyPart Htmlpart = new MimeBodyPart (); The order of assembly is very important bodymultipart.addbodypart (Htmlpart); 
    MimeBodyPart IN_BG = new MimeBodyPart (); 
 
    Bodymultipart.addbodypart (IN_BG); 
    DataSource Bgsou = new Filedatasource (Mail.getbgpath ()); 
    DataHandler bghd = new DataHandler (Bgsou); 
    In_bg.setdatahandler (BGHD); 
    In_bg.setheader ("Content-location", "bg.jpg"); Do you use background music if (null = Mail.getmusicpath ()) | | 
      "". Equals (Mail.getmusicpath ()) {String start = " 

We sent the mail to C, you can go to the C check, if you need to actually send, you can refer to my other blog, have a special description!

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.