【问题标题】:send an e-mail to the text "e-mail" which is in the textbox向文本框中的文本“电子邮件”发送电子邮件
【发布时间】:2011-04-12 14:34:44
【问题描述】:

我的 jsp 中有一个文本框,我想向在文本框中输入他/她的电子邮件的收件人发送一封电子邮件。

请您指导我如何做到这一点。

我刚刚检查了这段代码:

<html>
<head>
    <title>mailto Example</title>
</head>

<body>
<form action="mailto:XXX@XXX.com" method="post" enctype="text/plain" >
FirstName:<input type="text" name="FirstName">
Email:<input type="text" name="Email">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

【问题讨论】:

  • 您想在用户系统上打开本地邮件客户端,还是想从您的服务器发送电子邮件?

标签: java javascript email jsp smtp


【解决方案1】:

您需要将表单发布到 servlet 并从 servlet 执行此方法以发送邮件。 你的表格应该是

<form action="sendMail.do" method="post" enctype="text/plain" >
FirstName:<input type="text" name="FirstName">
Email:<input type="text" name="Email">
<input type="submit" name="submit" value="Submit">
</form>

这是从 java 发送电子邮件的代码,在 web.xml 中为 servlet 做正确的映射
对于 servlet 教程,请查看 here

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException
{
    boolean debug = false;

     //Set the host smtp address
     Properties props = new Properties();
     props.put("mail.smtp.host", "smtp.jcom.net");

    // create some properties and get the default Session
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);

    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length]; 
    for (int i = 0; i < recipients.length; i++)
    {
        addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);


    // Optional : You can also set your custom headers in the Email if you Want
    msg.addHeader("MyHeaderName", "myHeaderValue");

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);
}

【讨论】:

  • 我可以在同一个jsp中做到这一点吗?只是为了测试
  • 可以,我不推荐,最好放在Servlet上,
【解决方案2】:

执行此操作的常用方法是使用一些服务器端脚本,例如在 php 中,它将获取表单的值,从中创建一封电子邮件并发送。

表单数据当然可以通过 javascript / ajax 发送,但我认为在使用 php 脚本时没有必要。

【讨论】:

    猜你喜欢
    • 2017-11-01
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多