发布日期:2018-03-26
我怎么通过Java应用来使用Gamil,Yahoo或者Hotmail发送一个邮件?+ 查看更多
我怎么通过Java应用来使用Gamil,Yahoo或者Hotmail发送一个邮件?
+ 查看更多
发布日期:2018-02-23 16:34
分类:JAVA
浏览次数:315
有没有可能通过我的Java应用去使用Gamil账号来发送一个邮件?
我已经通过Java应用配置了我公司的有服务器来发送邮件,但是当我分配这个应用时用不了了。
只要是使用了Hotmail,Yahoo或者Gmail的答案都是可以接受的。
回答:
首先你在下载 JavaMail API 然后确定相关的JAR文件在你的类路径中。
这里是完整的使用了Gmail的例子。
import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class Main { private static String USER_NAME = "*****"; // GMail user name (just the part before "@gmail.com") private static String PASSWORD = "********"; // GMail password private static String RECIPIENT = "lizard.bill@myschool.edu"; public static void main(String[] args) { String from = USER_NAME; String pass = PASSWORD; String[] to = { RECIPIENT }; // list of recipient email addresses String subject = "Java send mail example"; String body = "Welcome to JavaMail!"; sendFromGMail(from, pass, to, subject, body); } private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) { Properties props = System.getProperties(); String host = "smtp.gmail.com"; props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.user", from); props.put("mail.smtp.password", pass); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); InternetAddress[] toAddress = new InternetAddress[to.length]; // To get the array of addresses for( int i = 0; i < to.length; i++ ) { toAddress[i] = new InternetAddress(to[i]); } for( int i = 0; i < toAddress.length; i++) { message.addRecipient(Message.RecipientType.TO, toAddress[i]); } message.setSubject(subject); message.setText(body); Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (AddressException ae) { ae.printStackTrace(); } catch (MessagingException me) { me.printStackTrace(); } } }
当然,我知道比起我在catch块中打印堆栈轨迹,你会想要做的更多。
删除块看哪个方法调用从JavaMail API抛出异常,所以你可以看到如何妥善处理。