2

我在从我的应用程序发送邮件时遇到问题。我不能在我的应用程序上使用简单的 SMTP 服务器。并且不知道如何处理在 JAVA 中发送邮件。我应该使用与 PHP 的 mail() 相同/相似的机制。不幸的是,我不知道该怎么做。

4

4 回答 4

5

Java Mail API支持发送和接收电子邮件。API 提供了一种插件架构,在该架构中,可以在运行时动态地发现和使用供应商对其专有协议的实现。Sun 提供了一个参考实现,它支持以下协议:

  • 互联网邮件访问协议 (IMAP)
  • 简单邮件传输协议 (SMTP)
  • 邮局协议 3 (POP 3)

以下是如何使用它的示例:

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMail {

    private String from;
    private String to;
    private String subject;
    private String text;

    public SendMail(String from, String to, String subject, String text){
        this.from = from;
        this.to = to;
        this.subject = subject;
        this.text = text;
    }

    public static void main(String[] args) {

            String from = "abc@gmail.com";
            String to = "xyz@gmail.com";
            String subject = "Test";
            String message = "A test message";
            SendMail sendMail = new SendMail(from, to, subject, message);
            sendMail.send();
    }

    public void send(){

        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "465");
        Session mailSession = Session.getDefaultInstance(props);
        Message simpleMessage = new MimeMessage(mailSession);
        InternetAddress fromAddress = null;
        InternetAddress toAddress = null;
        try {
            fromAddress = new InternetAddress(from);
            toAddress = new InternetAddress(to);
        } catch (AddressException e) {
            e.printStackTrace();
        }

        try {
            simpleMessage.setFrom(fromAddress);
            simpleMessage.setRecipient(RecipientType.TO, toAddress);
            simpleMessage.setSubject(subject);
            simpleMessage.setText(text);    
            Transport.send(simpleMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
于 2013-02-10T23:24:36.077 回答
2

您需要检查JavaMail API,并且根据 PHP 的 mail() 的要求,它需要一个 SMTP 服务器来发送该电子邮件。

如果您需要 SMTP 服务器,我建议您在 Google 中搜索适合您操作系统的 SMTP 服务器,或者您可以使用 ISP 或服务器主机提供的 SMTP 服务器。

于 2013-02-10T23:19:02.580 回答
0

您可以将 JavaMail api 与Apache James等本地 SMTP 服务器一起使用,因此在安装并运行 James 服务器后,您可以将 SMTP 服务器 ip 设置为127.0.0.1

于 2013-02-10T23:51:51.770 回答
0

我应该使用与 PHP 的 mail() 相同/相似的机制。

你不能,因为它不存在。如果这是要求,请更改它。

不幸的是,我不知道该怎么做。

请参阅 JavaMail API。

于 2013-02-11T00:51:22.877 回答