本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
How do you send email from a Java app using Gmail?
如何从Java发送SMTP消息?
这是Gmail smtp的示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| 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/
问候
Tov Are Jacobsen
另一种方法是像这样使用阿司匹林(https://github.com/masukomi/aspirin):
1
| MailQue.queMail(MimeMessage message) |
..在完成上述模仿后。
阿司匹林是smtp的"服务器",因此您无需进行配置。但是请注意,将电子邮件发送给广泛的收件人并不像它看起来的那么简单,因为接收邮件服务器和客户端应用程序采用多种不同的垃圾邮件过滤规则。
请看这篇文章
如何通过Java应用程序使用GMail,Yahoo或Hotmail发送电子邮件?
它特定于gmail,但您可以替换您的smtp凭据。
请参阅JavaMail API和关联的javadocs。
请参阅Java实践中的以下教程。
http://www.javapractices.com/topic/TopicAction.do?Id=144
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| 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);
} |