Java操作应用——邮件发送
在Java中发送邮件也很简单。你只需装一下Java Mail这个jar包,放到你的类路径里即可。在下面的代码中,我们设置了几个基础属性,然后便可以发送邮件了:
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 | import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class SendEmail { public static void main(String [] args) { String to = "recipient@gmail.com" ; String from = "sender@gmail.com" ; String host = "localhost" ; Properties properties = System.getProperties(); properties.setProperty( "mail.smtp.host" , host); Session session = Session.getDefaultInstance(properties); try { MimeMessage message = new MimeMessage(session); message.setFrom( new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject( "My Email Subject" ); message.setText( "My Message Body" ); Transport.send(message); System.out.println( "Sent successfully!" ); } catch (MessagingException ex) { ex.printStackTrace(); } } } |
点击加载更多评论>>