java 代码
- public class EMail {
- Properties props = new Properties();
- Session sendMailSession;
- Store store;
- Transport transport;
- String usr = ""; //这里填写你发信者的邮箱地址
- String pwd = ""; //这里填写你发信者的邮箱密码
- String smtpServer = ""; //这里填写smtp服务器的名称
- String mailContent = ""; //这里填写邮件内容
- String toAddress = ""; //这里填写收件人的地址;
- String fromAddress = ""; //这里填写发件人的地址
- String mailSubject = ""; //填写邮件的主题
- public EMail() {
- }
- public boolean Init() {
- try {
- Properties p = new Properties();
- String fileName = "/ApplicationResources.properties"; //指定资源文件
- InputStream is = getClass().getResourceAsStream(fileName); //打开资源文件
- p.load(is); //装载资源文件
- this.smtpServer=p.getProperty("mail.smtp.host");
- this.usr=p.getProperty("mail.from.user");
- this.pwd=p.getProperty("mail.from.psw");
- this.fromAddress=p.getProperty("mail.from.address");
- } catch (Exception ex) {
- return false;
- }
- return true;
- }
- public boolean SendMail() {
- try {
- props.put("mail.smtp.host",smtpServer); //这里填写你发信者的SMTP主机,如:smtp.sohu.com
- props.put("mail.smtp.user", usr);
- props.put("mail.smtp.password", pwd);
- props.put("mail.smtp.auth", "true");
- sendMailSession = Session.getInstance(props, new Authenticator() {
- public PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(usr,pwd);
- } //这里填写你发信者的邮箱地址和密码
- }); //如果邮箱是SMTP验证的,就得这么写。否则会报错。Session.getInstance(props)这个方法是针对SMTP不要求验证的,我的邮箱要验证,所以得这么写。
- Message newMessage = new MimeMessage(sendMailSession);
- newMessage.setFrom(new InternetAddress(fromAddress));
- newMessage.setRecipient(Message.RecipientType.TO,
- new
- InternetAddress(toAddress));
- newMessage.setSubject(mailSubject);
- newMessage.setSentDate(new Date());
- newMessage.setText(mailContent);
- transport = sendMailSession.getTransport("smtp");
- transport.send(newMessage);
- } catch (Exception m) {
- m.printStackTrace();
- return false;
- }
- return true;
- }