简体   繁体   中英

How attach file attachments to mail using jsp?

There is one JSP page in which there is button ,on click of that i want to attach the file into mail without send it, using JSP?

I am using mailto tag on click of that button due to which i am able to get login to gmail and i am able to pass subject in mail but i don't know how to attach any file in that using jsp or java?

If anybody knows , that how to do it then please tell me.

No, you can not add an attachment to a message with the mailto.

mailto: only supports header values or text/plain content.

   public class SendMail {

    public SendMail() throws MessagingException {

        String host = "smtp.gmail.com";
        String Password = "mnmnn";
        String from = "xyz@gmail.com";
        String toAddress = "abc@gmail.com";
        String filename = "C:/Users/hp/Desktop/Write.txt";
        // Get system properties
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtps.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        Session session = Session.getInstance(props, null);

        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(from));

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

        message.setSubject("JavaMail Attachment");

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Here's the file");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        try {
            Transport tr = session.getTransport("smtps");
            tr.connect(host, from, Password);
            tr.sendMessage(message, message.getAllRecipients());
            System.out.println("Mail Sent Successfully");
            tr.close();

        } catch (SendFailedException sfe) {

            System.out.println(sfe);
        }
    }
}

Note : Use JavaMail API .

    //Mail.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <%@include file="Database.jsp" %>
    <%@page import="java.sql.Statement"%>
    <%@page import="java.sql.ResultSet"%>
    <html>
        <head>
        </head>
    <body>  
     <form id="form1" class="blocks" action="AttachMail.jsp" method="post" enctype="multipart/form-data">
           <table width="500px"  border="0">
            <tr>
                <td style="color:#BAA111" align="center"><h4><b>File Upload</b></h4></td>
            </tr>
            <tr>
                <td style="width:200px;">
                    <hr style="width:410px" align="left"></hr>
                </td>
            </tr>
        </table><br>
                <p>
                    <label>First Name:</label>
                    <input type="text" name="fname" class="text"/>
                </p>
                <p>
                    <label>Last Name:</label>
                    <input type="text" name="lname" class="text"/>
                </p>
                <p>
                    <label>Email ID:</label>
                    <input type="text" name="email" class="text"/>
                </p>
                <p>         
                    <label>Upload File:</label>             
                    <input type="file" name="file" class="file"/>           
                </p>
                <p><br>
                    <label>&nbsp;&nbsp;&nbsp;</label>
                    <input type="submit" class="btn" value="Submit"/>
                    <label style="width:10px"></label>
                    <input type="reset" class="btn" value="Reset"/>
                </p>          
         </form>  
    </body>
    </html>


    //AttachMail.jsp

    <%@ page import="java.util.*,java.io.*,javax.mail.*,javax.mail.internet.*,javax.activation.*,org.apache.commons.fileupload.*,org.apache.commons.fileupload.servlet.*,org.apache.commons.fileupload.disk.*,org.apache.commons.fileupload.util.*" %>
    <html>
    <body>
        <%
        String subject="Sending Mail with Attachment and Form data";//This is fixed subject, you may get from "form" also
        String body="";

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(request);
            FileItemStream item = null;
            String fname = null; //you may write different names also
            String lname = null; // or put in default value  
            String email = null; //  for these fields
            String file = null;
            InputStream stream = null;
            //out.print("mulipart request received<br/>");
            while (iter.hasNext()) {
                item = iter.next();
                String fdname = item.getFieldName();
                stream = item.openStream();
                if (item.isFormField()) {
                    String fieldValue = Streams.asString(stream);
                    //out.print("Form field " + name + " with value "   + fieldValue + "<br/>");
                    if ("fname".equals(fdname)){
                         body ="First Name : "+ fieldValue+"\n";
                    }
                    if ("lname".equals(fdname)){
                        body =body+"Last Name : "+ fieldValue+"\n";
                    }
                    if ("email".equals(fdname)){
                        email=fieldValue;
                        body =body+"Email Id : "+ fieldValue+"\n";
                    }
                }

                else {
                    fdname = item.getName();
                    if (fdname != null && !"".equals(fdname.trim())) 
                    {
                        file = new File(item.getName()).getName();

                        FileDataSource fds = new FileDataSource(file);
                    try{
                        Properties props = new Properties(); //we could enter properties later
                        props.put("mail.smtp.auth", "true");
                        Session s = Session.getInstance(props, null);
                        MimeMessage msg = new MimeMessage(s);
                        msg.setFrom(new InternetAddress(email));
                        msg.addRecipient(Message.RecipientType.TO,new InternetAddress("To mail address"));//or you can pass from form also
                        msg.setSubject(subject);
                        MimeBodyPart mbp1 = new MimeBodyPart();
                        mbp1.setText(body);
                        MimeBodyPart mbp2 = new MimeBodyPart();
                        mbp2.setDataHandler(new DataHandler(fds));
                        mbp2.setFileName(fds.getName());
                        Multipart mp = new MimeMultipart();
                        mp.addBodyPart(mbp1);
                        mp.addBodyPart(mbp2);
                        msg.setContent(mp);
                        msg.saveChanges();
                        Transport transport=s.getTransport("smtp");
                        transport.connect("smtp domain name","email address","password");
                        transport.sendMessage(msg,msg.getAllRecipients());
                        transport.close();
                    }
                    catch(Exception e)
                    {
                        e.printStackTrace();
                    }
                   } 
                    else
                        out.print("File or necessary fields were not sent !<br/>");
                }
            }
        } else
            out.print("request was not multipart");
    %>
    </body>
    </html> 

//jar files to add "mail.jar, naming-factory-4.1.31.jar, org.apache.commons.fileuplod.jar"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM