用JavaMail发送和接收邮件

本文介绍如何使用JavaMail API实现发送带有文本内容及附件的电子邮件,并演示了接收邮件及解析附件的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用JavaMail发送邮件
package com.mailsystem.example;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendAttachment
...{
public static void main(String[] args)
...{
try
...{
// 创建 properties ,里面包含了发送邮件服务器的地址。
Properties mailProps = new Properties();
mailProps.put("mail.smtp.host", "127.0.0.1");

// 创建 session
Session mailSession = Session.getDefaultInstance(mailProps);

// 创建 邮件的message,message对象包含了邮件众多有的部件,都是封装成了set方法去设置的
MimeMessage message = new MimeMessage(mailSession);

//设置发信人
message.setFrom(new InternetAddress(
"fred@testmail.com"));
//收信人
message.setRecipient(Message.RecipientType.TO,
new InternetAddress("tang@testmail.com"));

// 邮件标题
message.setSubject("a poem");


//创建附件
MimeMultipart multi = new MimeMultipart();

// 创建 BodyPart,主要作用是将以后创建的n个内容加入MimeMultipart.也就是可以发n个附件

BodyPart textBodyPart = new MimeBodyPart(); //第一个BodyPart.主要写一些一般的信件内容。

textBodyPart.setText("Do you fear the force of the wind The slash of the rain Go face them and fight them "+
"Be savage again. Go hungry and cold like the wolf, Go wade like the crane: "+
"The palms of your hands will thicken, The skin of your cheek will tan, You'll grow ragged and weary and swarthy, "+
"But you'll walk like a man!");

// 压入第一个BodyPart到MimeMultipart对象中。
multi.addBodyPart(textBodyPart);

// 创建第二个BodyPart,是一个FileDataSource
FileDataSource fds = new FileDataSource("e:\注册码.txt");

BodyPart fileBodyPart = new MimeBodyPart(); //第二个BodyPart
fileBodyPart.setDataHandler(new DataHandler(fds)); //字符流形式装入文件
fileBodyPart.setFileName(fds.getName()); //设置文件名,可以不是原来的文件名。

multi.addBodyPart(fileBodyPart);

// MimeMultPart作为Content加入message
message.setContent(multi);

// 所有以上的工作必须保存。
message.saveChanges();

Transport.send(message);
System.out.println("Mail send succesfully!");

} catch (Exception e) ...{
e.printStackTrace();
}
}
}


用JavaMail接收邮件
package com.mailsystem.example;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Provider;

public class MailReciever ...{
public static final String mailServer = "127.0.0.1";
public static final String mailUserName = "tang";
public static final String mailPassword = "tang";
public static final String mailProvider = "imap";

//解析邮件内容
private static void extractPart(final Part part) throws MessagingException, IOException ...{
if(part.getContent() instanceof Multipart) ...{
Multipart mp=(Multipart)part.getContent();
for(int i=0;i<mp.getCount();i++) ...{
extractPart(mp.getBodyPart(i));
}
return;
}
String fileName = part.getFileName();

if(fileName == null) ...{
System.out.println(part.getContent());
} else if(fileName != null && !part.getContentType().startsWith("text/plain")) ...{
//解析附件内容

InputStream in=part.getInputStream();
//保存附件,这里假设了一个文件,实际应该根据保存文件的类型来决定
FileOutputStream out = new FileOutputStream("e:\att.txt");

byte[] buffer=new byte[1024];
int count=0;
while((count=in.read(buffer))>=0)
out.write(buffer,0,count);
in.close();
}
}

public static void main(String []args) ...{
Properties props = new Properties();

props.setProperty("mail.pop3s.rsetbeforequit","true");
props.setProperty("mail.pop3.rsetbeforequit","true");
Session session=Session.getInstance(props,null);
try ...{
System.out.println("Getting store...");
Store store = session.getStore(mailProvider);

store.connect(mailServer, mailUserName, mailPassword);

Folder folder = store.getFolder("inbox");

folder.open(Folder.READ_WRITE);

System.out.println("You have " + folder.getMessageCount() + " messages in inbox");
System.out.println("You hava " + folder.getUnreadMessageCount() + " unread messages in inbox");
Message []msgs = folder.getMessages();

for (int i=0; i < msgs.length; i++) ...{

MailReciever.extractPart(msgs[i]);

}
folder.close(false); //false:不删除标记为DELETED的邮件
store.close();
} catch (Exception ex) ...{
ex.printStackTrace();
}

}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值