---
title: "jmail发送邮件---转别人的。"
author: "zengyan2012"
date: "2014-09-26T17:15:22Z"
tags: []
categories: ["移动开发"]
slug: "jmail"
draft: false
lastmod: "2014-09-26T17:15:22Z"
id: 2122774
url: "https://zengyan2012.iteye.com/blog/2122774"
---

需要jar包：

mail.jar

additionnal.jar

activation.jar

 

public void sendEMail(final Context context) {

new Thread(new Runnable() {

 

@Override

public void run() {

 

UserInfoVo vo = UserInfoVo.getInstance(context);

 

try {

 

String userName = "邮箱@126.com";

String password = "密码";

String smtp\_server = "smtp.126.com";

String from\_mail\_address = userName;

String to\_mail\_address = "发给谁@qq.com";

Authenticator auth = new PopupAuthenticator(userName,

password);

Properties mailProps = new Properties();

mailProps.put("mail.smtp.host", smtp\_server);

mailProps.put("mail.smtp.auth", "true");

mailProps.put("username", userName);

mailProps.put("password", password);

 

Session mailSession = Session.getDefaultInstance(mailProps,

auth);

mailSession.setDebug(true);

MimeMessage message = new MimeMessage(mailSession);

message.setFrom(new InternetAddress(from\_mail\_address));

message.setRecipient(Message.RecipientType.TO,

new InternetAddress(to\_mail\_address));

message.setSubject("校通");

 

SharedPreferences sp = context.getSharedPreferences("user",

Context.MODE\_PRIVATE);

 

MimeMultipart multi = new MimeMultipart();

BodyPart textBodyPart = new MimeBodyPart();

textBodyPart.setText("" + vo.getSchoolName() + "---"

\+ vo.getClassName() + "--" + vo.getRealName()

\+ "---" + sp.getString("key", ""));

 

multi.addBodyPart(textBodyPart);

message.setContent(multi);

message.saveChanges();

Transport.send(message);

} catch (Exception ex) {

System.err.println("邮件发送失败的原因是：" + ex.getMessage());

System.err.println("具体的错误原因");

ex.printStackTrace(System.err);

}

}

}).start();

}

 

// public static void main(String\[] args) {

//

// }

}

 

class PopupAuthenticator extends Authenticator {

private String username;

private String password;

 

public PopupAuthenticator(String username, String pwd) {

this.username = username;

this.password = pwd;

}

 

public PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(this.username, this.password);

}