如何从 Java 发送 SMTP 消息?
Allain Lalonde
问问题
96484 次
6 回答
36
以下是 Gmail smtp 的示例:
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.mail.internet.*;
import com.sun.mail.smtp.*;
public class Distribution {
public static void main(String args[]) throws Exception {
Properties props = System.getProperties();
props.put("mail.smtps.host","smtp.gmail.com");
props.put("mail.smtps.auth","true");
Session session = Session.getInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("mail@tovare.com"));;
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("tov.are.jacobsen@iss.no", false));
msg.setSubject("Heisann "+System.currentTimeMillis());
msg.setText("Med vennlig hilsennTov Are Jacobsen");
msg.setHeader("X-Mailer", "Tov Are's program");
msg.setSentDate(new Date());
SMTPTransport t =
(SMTPTransport)session.getTransport("smtps");
t.connect("smtp.gmail.com", "admin@tovare.com", "<insert password here>");
t.sendMessage(msg, msg.getAllRecipients());
System.out.println("Response: " + t.getLastServerResponse());
t.close();
}
}
现在,仅当您希望将项目依赖项保持在最低限度时才这样做,否则我可以热烈推荐使用来自 apache 的类
http://commons.apache.org/email/
问候
托夫是雅各布森
于 2008-09-16T15:34:30.413 回答
6
另一种方法是像这样使用阿司匹林(https://github.com/masukomi/aspirin):
MailQue.queMail(MimeMessage message)
..在构建了你的 mimemessage 之后。
Aspirin是一个 smtp 的“服务器”,因此您不必对其进行配置。但请注意,向广泛的收件人发送电子邮件并不像看起来那么简单,因为接收邮件服务器和客户端应用程序应用了许多不同的垃圾邮件过滤规则。
于 2008-09-18T04:25:28.027 回答
3
于 2008-09-16T15:29:58.990 回答
2
请参阅JavaMail API和相关的 javadocs。
于 2008-09-16T15:29:42.720 回答
2
请参阅 Java 实践中的以下教程。
于 2008-09-16T15:30:05.357 回答
1
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public void postMail(String recipients[], String subject,
String message , String from) throws MessagingException {
//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(false);
// 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);
}
于 2011-01-02T14:53:46.937 回答