繁体   English   中英

从Java发送邮件

[英]Sending mail from java

用Java发送和接收邮件的最简单方法是什么。

不要忘记Jakarta Commons Email发送邮件。 它具有非常易于使用的API。

JavaMail是发送电子邮件的传统答案(正如每个人都指出的那样)。

但是,由于您也想接收邮件,因此应该查看Apache James 这是一个模块化的邮件服务器,可进行大量配置。 它将讨论POP和IMAP,支持自定义插件,并且可以嵌入到您的应用程序中(如果您愿意的话)。

签出这个包。 在链接中,这是一个代码示例:

Properties props = new Properties();
props.put("mail.smtp.host", "my-mail-server");
props.put("mail.from", "me@example.com");
Session session = Session.getInstance(props, null);

try {
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom();
    msg.setRecipients(Message.RecipientType.TO,
                      "you@example.com");
    msg.setSubject("JavaMail hello world example");
    msg.setSentDate(new Date());
    msg.setText("Hello, world!\n");
    Transport.send(msg);
} catch (MessagingException mex) {
    System.out.println("send failed, exception: " + mex);
}
try {
Properties props = new Properties();
props.put("mail.smtp.host", "mail.server.com");
props.put("mail.smtp.auth","true");
props.put("mail.smtp.user", "test@server.com");
props.put("mail.smtp.port", "25");
props.put("mail.debug", "true");

Session session = Session.getDefaultInstance(props);

MimeMessage msg = new MimeMessage(session);

msg.setFrom(new InternetAddress("test@server.com"));

InternetAddress addressTo = null;
addressTo = new InternetAddress("test@mail.net");
msg.setRecipient(javax.mail.Message.RecipientType.TO, addressTo);

msg.setSubject("My Subject");
msg.setContent("My Message", "text/html; charset=iso-8859-9");

Transport t = session.getTransport("smtp");   
t.connect("test@server.com", "password");
t.sendMessage(msg, msg.getAllRecipients());
t.close();
} catch(Exception exc) {
  exc.printStackTrace();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM