【原创】java使用gamil发信


//此代码只需要导mail.jar 即可发信,本人反复测试都ok

package com.zwj.struts.action;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * 
 * 模块功能:发邮件 以下Java代码可以实现使用SMTP登陆到Gmail中并使用Gmail发送邮件
 */
public class SendMail_gmail {
	public static void main(String[] args) {
		String smtp_host = "smtp.gmail.com";
		String from_userName = "uutool";// 发件人账号
		String from_passWord = "******";// 发件人密码
		String sendSubject = "你的优优源创下载基地(uutool)登录密码";// 主题
		String sendText = "你的优优源创登录密码是:123 请用此密码重新登录  提示:请尽快删除本邮件以免密码泄露 .";// 内容
		String[] recipients = { "[email protected]" }; // 收件人

		
		sendMail(smtp_host, from_userName, from_passWord, recipients,
				sendSubject, sendText);
	}

	//发送邮件
	public static void sendMail(String smtp_host, String from_userName,
			String from_passWord, String[] recipients, String sendSubject,
			String sendText) {
		try {
			Properties props = System.getProperties();
			// 现在的大部分smpt都需要验证了
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.smtp.host", smtp_host);
			props.put("mail.smtp.user", from_userName);
			props.put("mail.smtp.password", from_passWord);
			props.put("mail.smtp.port", "587");
			props.put("mail.smtp.auth", "true");
			String[] to = recipients; // 收件人
			Session session = Session.getDefaultInstance(props, null);
			session.setDebug(true);
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(from_userName));
			InternetAddress[] toAddress = new InternetAddress[to.length];
			// 获取地址的array
			for (int i = 0; i < to.length; i++) {
				toAddress[i] = new InternetAddress(to[i]);
			}
			System.out.println(Message.RecipientType.TO);

			for (int i = 0; i < toAddress.length; i++) {
				message.addRecipient(Message.RecipientType.TO, toAddress[i]);
			}
			message.setSubject(sendSubject);
			message.setText(sendText);
			Transport transport = session.getTransport("smtp");
			transport.connect(smtp_host, from_userName, from_passWord);
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
			props.put("mail.smtp.user", from_userName);
			props.put("mail.smtp.password", from_passWord);
			System.out.println("邮件发送成功!");
		} catch (Exception e) {
			System.out.println("邮件发送失败! ");

		}
	}

}




你可能感兴趣的:(java,struts,Gmail)