Java-从jsp页面发送电子邮件

问题描述 投票:0回答:1

我的Web应用程序上有一个简单的JSP页面,如下所示:

enter image description here

输入收件人电子邮件,主题和内容后,用户可以在下方按下按钮。

我想实现一个允许用户向外人发送电子邮件的功能。我想到的是使用带有SMTP的Java Mail API。

所以,在我的后端代码中,我编写了一个如下所示的函数:

public String sendEmail(ArrayList mediaList, String authRequired, String TLSEnabled, String SSLEnabled, String smtpHost, String senderAddress, String portNumber, String user, String password,
                            String msgSubject, String msgContent,
                            ArrayList toRecipientAdd, ArrayList ccRecipientAdd, ArrayList bccRecipientAdd) {
        try {

            final String SenderAddress = senderAddress;
            final String Username = user;
            final String Password = password;


            System.out.println("Please Wait, sending email...");

            if (toRecipientAdd.size() == 0) {
                System.out.println("NO USER FOUND IN TORECIPIENT ADDRESS.");
                return "NO USER FOUND IN TORECIPIENT ADDRESS.";
            }

            if (msgSubject.equals("")) {
                System.out.println("MESSAGE SUBJECT NOT FOUND.");
                return "MESSAGE SUBJECT NOT FOUND.";
            }

            if (msgContent.equals("")) {
                System.out.println("MESSAGE CONTENT NOT FOUND.");
                return "MESSAGE CONTENT NOT FOUND.";
            }



            /*Setup mail server */

            Properties props = new Properties();
            props.put("mail.transport.protocol", "smtp");
            props.put("mail.smtp.auth", authRequired);
            props.put("mail.smtp.host", smtpHost);
            props.put("mail.smtp.port", portNumber);
            props.put("mail.smtp.starttls.enable", TLSEnabled);
            props.put("mail.smtp.ssl.trust", SSLEnabled);

            String auth_enable = authRequired;
            final String username = user;
            final String upassword = password;

            System.out.println("mail.smtp.host : " + smtpHost + " mail.smtp.port : " + portNumber);

            // Get session
            Session session = Session.getDefaultInstance(props, null);

            if(Boolean.parseBoolean(auth_enable)){
                session = Session.getInstance(props,
                        new javax.mail.Authenticator() {

                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(username, upassword);
                            }
                        });
            }

            session.setDebug(true);



            // Define message
            MimeMessage message = new MimeMessage(session);
            InternetAddress senderInetAddress = null;
            try {
                senderInetAddress = new InternetAddress(senderAddress);
            } catch (AddressException addressException) {
                addressException.printStackTrace();
            }

            // Set From Sender Address
            message.setFrom(senderInetAddress);

            // TO Recipient
            Iterator itr = toRecipientAdd.iterator();
            while (itr.hasNext()) {
                String receiverAddr = (String) itr.next();

                System.out.println("receiverAddr : " + receiverAddr);

                InternetAddress receiverInetAddress;
                try {
                    receiverInetAddress = new InternetAddress(receiverAddr);
                } catch (AddressException addressException) {
                    addressException.printStackTrace();
                    continue;
                }
                message.addRecipient(Message.RecipientType.TO, receiverInetAddress);
            }

            // CC Recipient
            Iterator i = ccRecipientAdd.iterator();
            while (i.hasNext()) {
                String ccAddr = (String) i.next();
                InternetAddress ccInetAddress = null;
                try {
                    ccInetAddress = new InternetAddress(ccAddr);
                } catch (AddressException addressException) {
                    addressException.printStackTrace();
                    continue;
                }
                message.addRecipient(Message.RecipientType.CC, ccInetAddress);
            }

            // BCC Recipient
            Iterator j = bccRecipientAdd.iterator();
            while (j.hasNext()) {
                String bccAddr = (String) j.next();
                InternetAddress bccInetAddress = null;
                try {
                    bccInetAddress = new InternetAddress(bccAddr);
                } catch (AddressException addressException) {
                    addressException.printStackTrace();
                    continue;
                }
                message.addRecipient(Message.RecipientType.BCC, bccInetAddress);
            }


            message.setSubject(msgSubject);

            Multipart mp = new MimeMultipart();
            MimeBodyPart htmlPart = new MimeBodyPart();

            htmlPart.setHeader("Content-Transfer-Encoding", "base64");
            htmlPart.setContent(msgContent, "text/html; charset=ISO-8859-1");
            htmlPart.setDisposition(javax.mail.Part.INLINE);
            mp.addBodyPart(htmlPart);

            Iterator mediaIter = mediaList.iterator();
            while(mediaIter.hasNext()){
                Fmedia fmedia = (Fmedia) mediaIter.next();
                DataSource fds = new FileDataSource(fmedia.getFfulpath() + "/" + fmedia.getFgname());

                MimeBodyPart imagePart = new MimeBodyPart();
                imagePart.setDataHandler(new DataHandler(fds));

                // assign a cid to the image
                imagePart.setHeader("Content-Transfer-Encoding", "base64");
                imagePart.addHeader("Content-ID", "<img" + fmedia.getNodeid() + ">");
                imagePart.setDisposition(javax.mail.Part.INLINE);

                mp.addBodyPart(imagePart);
            }

            message.setContent(mp);

            System.out.println("Sending.... ");

            // Send the message
            try{

                Transport.send(message, message.getAllRecipients());
                System.out.println("Message sent.");

            }catch(Exception e){
                e.printStackTrace();
                System.out.println("Exception " + e.getMessage());
            }
            return "";
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return e.getMessage();
        }
    }

但是,我仍然不熟悉Java中的SMTP,并且不知道props中应该指定的值是什么,而且因为我没有硬编码Mimemessage,所以我需要从JSP页面获取值,如上所示。

这可能吗?

java email
1个回答
1
投票

你在道具中设置了一些参数,比如

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");

如果您需要进一步说明,请参阅下面的示例代码,

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailSSL {
    public static void main(String[] args) {
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class",
            "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("username","password");
            }
        });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("[email protected]"));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("[email protected]"));
        message.setSubject("Testing Subject");
        message.setText("Dear Mail Crawler," +
                "\n\n No spam to my email, please!");

        Transport.send(message);

        System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

}

此外,您可以将任何参数传递给sendEmail方法,并在代码上使用这些值。

© www.soinside.com 2019 - 2024. All rights reserved.