JavaMailメール送信プログラム


簡単なメール送信プログラム
本人テストに成功しましたので、ご安心ください
コードの一部をローカルパスに変更
propertiesの構成は次のとおりです.

mail.smtp.host=stmp.163.com
[email protected]
mail.smtp.auth=true
mail.transport.protocol=smtp
[email protected]
mail.password=yourpassword

Javaコード:

@Service("emailSenderService")
public class EmailSenderServiceImpl implements EmailSenderService {
	
	private Properties props;
	
	public EmailSenderServiceImpl() {
		InputStream in = getClass().getClassLoader().getResourceAsStream(
				"com/***/EmailHost.properties");
		props = new Properties();
		
		try {
			props.load(in);
		} catch (IOException e) {
			System.out.print("loading system config file error");
			e.printStackTrace();
		}
		
	//	System.out.println(props.getProperty("mail.smtp.host"));
	}

// toAddr  email, subject  , content  
	public void sendMail(String toAddr, String subject, String content) {	

		Session session = Session.getInstance(props, null);
		session.setDebug(true);

		try {
			MimeMessage msg = new MimeMessage(session);
			msg.setSubject(subject);
			
			msg.setSentDate(new Date());
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddr));
			msg.setContent(content, "text/html;charset=gbk");
			msg.saveChanges();
			
			Transport transport = session.getTransport("smtp");
			transport.connect(props.getProperty("mail.smtp.host"), 25,
					props.getProperty("mail.username"),
					props.getProperty("mail.password"));

			transport.sendMessage(msg, msg.getAllRecipients());
			transport.close();
		} catch (MessagingException mex) {
			mex.printStackTrace();
		}
	}
}