发送邮件

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;








	public static void sendMail() throws MailException {
		try {

			JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

			Properties props = new Properties();// 也可用Properties props =
			// System.getProperties();
			props.put("mail.smtp.host", "mail.test.com.cn");// 存??送?件服?器的信息
			props.put("mail.smtp.auth", "true");// 同?通???
			Session s = Session.getInstance(props, new Authenticator() {
				public PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication("[email protected]", "password");
				}
			});// 根据属性新建一个?件会?
			s.setDebug(true);

			MimeMessage message = new MimeMessage(s);// 由?件会?新建一个消息?象
			// InternetAddress from=new InternetAddress("[email protected]");
			// message.setFrom(from);//?置?件人
			// InternetAddress to=new InternetAddress("[email protected]");
			// message.setRecipient(Message.RecipientType.TO,to);//?置收件人,并?置其接收?型?TO
			// message.setSubject("TO jzb2b");//?置主?
			// message.setText("my test");//?置信件内容
			// message.setSentDate(new Date());//

			message.setHeader("Errors-To", "[email protected]");

			// use the true flag to indicate you need a multipart message
			MimeMessageHelper helper = new MimeMessageHelper(message, true, getCharset());

			helper.setFrom("[email protected]");
			helper.setTo("[email protected]");
			helper.setText("111111");
			helper.setSubject("222222");

			Transport transport = s.getTransport("smtp");
			transport.connect("mail.test.com.cn", "[email protected]", "passworld");

			transport.sendMessage(message, message.getAllRecipients());//

			// ((JavaMailSenderImpl) mailSender).send(message);
		}
		catch (MessagingException e) {
			e.printStackTrace();
		}
	}

	public static String getCharset() {
		return "iso-2022-jp";
	}

你可能感兴趣的:(发送邮件)