本文实例讲述了java实现基于SMTP发送邮件的方法。分享给大家供大家参考。具体实现方法如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.log4j.Logger; public class MailUtil { private static Logger logger = Logger.getLogger(MailUtil. class ); /** * 发送邮件 * * @param smtp * SMTP服务器 * @param user * 用户名 * @param password * 密码 * @param subject * 标题 * @param content * 邮件内容 * @param from * 发件人邮箱 * @param to * 收件人邮箱 */ public static void send(String smtp, final String user, final String password, String subject, String content, String from, String to) { try { Properties props = new Properties(); props.put( "mail.smtp.host" , smtp); props.put( "mail.smtp.auth" , "true" ); Session ssn = Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password); } }); MimeMessage message = new MimeMessage(ssn); //由邮件会话新建一个消息对象 InternetAddress fromAddress = new InternetAddress(from); //发件人的邮件地址 message.setFrom(fromAddress); //设置发件人 InternetAddress toAddress = new InternetAddress(to); //收件人的邮件地址 message.addRecipient(Message.RecipientType.TO, toAddress); //设置收件人 message.setSubject(subject); //设置标题 message.setText(content); //设置内容 message.setSentDate( new Date()); //设置发信时间 Transport transport = ssn.getTransport( "smtp" ); transport.connect(smtp, user, password); transport.sendMessage(message, message .getRecipients(Message.RecipientType.TO)); // transport.send(message); transport.close(); logger.info( "邮件发送成功" ); } catch (Exception e) { logger.warn( "邮件发送失败" , e); } } } |
希望本文所述对大家的java程序设计有所帮助。