首先需要下载一个javax.mail包,将包导入工程,然后,然后直接上代码了!
package com.javaee.email; import java.util.Properties; import javax.mail.Address; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendMail_Two { public static void main(String[] args) { String message = "这是利用java发送第一封邮件"; try { //第一个参数是QQ邮箱服务器(不同的邮箱是不同的服务器),第二个参数是邮件发送者,第三个是邮件发送者密码,第四个参数是邮件接收者,第五个参数是发送的邮件信息 sendMail("smtp.qq.com", "[email protected]", "*******", "[email protected]", message); } catch (Exception e) { e.printStackTrace(); } } /** * @param args add by zxx ,Feb 5, 2009 */ public static void sendMail(String smtpHost, String from,String password, String to,String message) throws Exception{ // TODO Auto-generated method stub Properties props = new Properties(); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.transport.protocol", "smtp"); Session session = Session.getInstance(props); session.setDebug(true); Message msg = new MimeMessage(session); msg.setText(message); msg.setFrom(new InternetAddress(from)); Transport transport = session.getTransport(); transport.connect(smtpHost, 25, from.split("@")[0], password); transport.sendMessage(msg, new Address[]{new InternetAddress(to)}); transport.close(); } }
另外值得注意的是,如果在程序运行过程中出现
进入发送邮件者的邮箱,找到设置,找到账户,在POP3/IMAP/SMTP选择开启POP3/SMTP服务。