您的位置:首页 > 编程语言 > Java开发

javamail 的使用

2014-04-26 23:51 447 查看
SMTP 是 25端口 接收邮件 pop3

1. 相关类

  InternetAddress 地址

 Properties:属性类

Authenticator:认证类

Session:链接类

Transport:发送信息类

MimeMessage: 发送的信息

MimeMultipart:附件信息

BodyPart:附件内容

MimeUtility:

2. 相关的配置文件

portcol=smtp

host=smtp.126.com

username=1111@126.com

password=22222222

port=25

3. 发送邮件的需要内容

 (1)from (InternetAddress ) to(InternetAddress)    认证

  (2)相关的代码

Properties props = new Properties();
props.put("mail.transport.protocol", Config.getEMAIL_PROTOCOL());
props.put("mail.smtp.host",Config.getEMAIL_HOST());
Authenticator auth = new EmailAuth(Config.getEMAIL_USERNAME(), Config.getEMAIL_PASSWORD());
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, auth);
MimeMessage message = new MimeMessage(session);
try {
Transport transport = session.getTransport(Config.getEMAIL_PROTOCOL());
transport.connect(Config.getEMAIL_HOST(),Config.getEMAIL_USERNAME(),Config.getEMAIL_PASSWORD());

message.setSubject(model.getTitle()); //主题
InternetAddress from=new InternetAddress(model.getFromAddress(),model.getShowName()); //发件人地址
message.setFrom(from);
InternetAddress to= new InternetAddress(model.getToMailaddress());
message.setRecipient(RecipientType.TO,to);

message.setSentDate(new Date());
String content1 = getHead()+getCommon();
if( null != model.getSendExtend()&& !model.getSendExtend().equals("")){

content1=content1+model.getSendExtend();
}
content1=content1+getPerson()+getRoot();

if(null != model.getPsfilename() && !"".equals(model.getPsfilename())){
String[] filename = model.getPsfilename().split("#");
MimeMultipart multipart = getMimeMultipart(content1,filename);
message.setContent(multipart);
}else{
message.setText(content1);
}
transport.sendMessage(message,message.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
其中:

message.setText() :发送文本形式的邮件

message.setContent() :发送html格式的邮件

private static MimeMultipart getMimeMultipart(String message, String[] fileName){
MimeMultipart multi = new MimeMultipart();
try {
BodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText(message); //将第一个BodyPart放到MimeMultipart对象中。
multi.addBodyPart(textBodyPart);
for(int i=0;i<fileName.length;i++){
FileDataSource fds = new FileDataSource(fileName[i]); //必须存在的文档,否则throw异常。
BodyPart fileBodyPart = new MimeBodyPart(); //第二个BodyPart
fileBodyPart.setDataHandler(new DataHandler(fds));
//字符流形式装入文件
fileBodyPart.setFileName(MimeUtility.encodeText(new File(fileName[i]).getName()));
multi.addBodyPart(fileBodyPart);
}
} catch (Exception e) {
e.printStackTrace();
}
return multi;
}


 使用命令行进行邮件发送接收:

win7 打开telnet:开始---控制面板----打开/关闭windows 服务 ----选择telnet 客户端

命令:

telnet smtp.126.com 25

ehlo 126.com 或者 helo 163.com

auth login 

出现334 等说明要输入用户名了,用户名要使用base64编码

然后出现334 则要输入密码,同样使用base64编码

mail from:<>

rcpt to:<>

Subject:标题

data 后写内容文件: 最后以"."结束

   输入 from:发件人名称  ,此项可任意填入,将显示在收件箱的‘发件人’一栏

     输入 to:收件人名称  ,可任意填入,将显示在收件箱的‘收件人’一栏

     输入 subject:信件主题   ,显示在收件箱的‘主题’一栏中

     此时需空一行,即在一空行直接回车,表示正文部分的开始

     空行后输入信件的正文内容。

     在正文输入结束时输入一个 . (英文输入法下的句号)回车,表示正文部分的结束。这时将显示邮件成功发送的信息。

接收邮件:

telnet pop3.163.com 110

user 用户名

pass 密码

常用命令:

1.stat命令 格式:stat 无需参数
 // 查看邮件的整体情况
2.list命令 格式:list 
 参数n可选,n为邮件编号  //查看n编码的邮件的信息
3.uidl命令 格式:uidl 
 同上  
4.retr命令 格式:retr n 参数n不可省,n为邮件编号  
5.dele命令 格式:dele n 同上  
6.top 命令 格式:top n m 参数n,m不可省,n为邮件编号,m为行数  
7.noop命令 格式:noop 无需参数  
8.quit命令 格式:quit 无需参数

javamail类介绍:

SMTPTransport 是具体的实现类:

其中sendMessage 方法:

(1)使用关键字synchronized进行修饰

public synchronized void sendMessage(Message message, Address[] addresses)
throws MessagingException, SendFailedException {

checkConnected();

// check if the message is a valid MIME/RFC822 message and that
// it has all valid InternetAddresses; fail if not
if (!(message instanceof MimeMessage)) {
if (debug)
out.println("DEBUG SMTP: Can only send RFC822 msgs");
throw new MessagingException("SMTP can only send RFC822 messages");
}
for (int i = 0; i < addresses.length; i++) {
if (!(addresses[i] instanceof InternetAddress)) {
throw new MessagingException(addresses[i] +
" is not an InternetAddress");
}
}

this.message = (MimeMessage)message;
this.addresses = addresses;
validUnsentAddr = addresses;	// until we know better
expandGroups();

boolean use8bit = false;
if (message instanceof SMTPMessage)
use8bit = ((SMTPMessage)message).getAllow8bitMIME();
if (!use8bit) {
String ebStr =
session.getProperty("mail." + name + ".allow8bitmime");
use8bit = ebStr != null && ebStr.equalsIgnoreCase("true");
}
if (debug)
out.println("DEBUG SMTP: use8bit " + use8bit);
if (use8bit && supportsExtension("8BITMIME")) {
if (convertTo8Bit(this.message)) {
// in case we made any changes, save those changes
// XXX - this will change the Message-ID
try {
this.message.saveChanges();
} catch (MessagingException mex) {
// ignore it
}
}
}

try {
mailFrom();
rcptTo();
this.message.writeTo(data(), ignoreList);
finishData();
if (sendPartiallyFailed) {
// throw the exception,
// fire TransportEvent.MESSAGE_PARTIALLY_DELIVERED event
if (debug)
out.println("DEBUG SMTP: Sending partially failed " +
"because of invalid destination addresses");
notifyTransportListeners(
TransportEvent.MESSAGE_PARTIALLY_DELIVERED,
validSentAddr, validUnsentAddr, invalidAddr,
this.message);

throw new SMTPSendFailedException(".", lastReturnCode,
lastServerResponse, exception,
validSentAddr, validUnsentAddr, invalidAddr);
}
notifyTransportListeners(TransportEvent.MESSAGE_DELIVERED,
validSentAddr, validUnsentAddr,
invalidAddr, this.message);
} catch (MessagingException mex) {
if (debug)
mex.printStackTrace(out);
notifyTransportListeners(TransportEvent.MESSAGE_NOT_DELIVERED,
validSentAddr, validUnsentAddr,
invalidAddr, this.message);

throw mex;
} catch (IOException ex) {
if (debug)
ex.printStackTrace(out);
// if we catch an IOException, it means that we want
// to drop the connection so that the message isn't sent
try {
closeConnection();
} catch (MessagingException mex) { /* ignore it */ }
notifyTransportListeners(TransportEvent.MESSAGE_NOT_DELIVERED,
validSentAddr, validUnsentAddr,
invalidAddr, this.message);

throw new MessagingException("IOException while sending message",
ex);
} finally {
// no reason to keep this data around
validSentAddr = validUnsentAddr = invalidAddr = null;
this.addresses = null;
this.message = null;
this.exception = null;
sendPartiallyFailed = false;
}
}


其实其内部使用的是发送命令的方式进行邮件的发送:

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javamail