当前位置:首页 » 编程语言 » java发送mail

java发送mail

发布时间: 2025-09-23 12:49:34

java 发送邮件 需要哪些jar包

使用JavaMail发送邮件需要用到mail.jar和activtion.jar两个包。

该类实现了较完整的邮件发送功能,包括以HTML格式发送,添加附件和抄送人。下面是具体的代码:

packagecn.cgw.util.mail;

importjava.util.Properties;

importjavax.activation.DataHandler;
importjavax.activation.FileDataSource;
importjavax.mail.Address;
importjavax.mail.BodyPart;
importjavax.mail.Message;
importjavax.mail.Multipart;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeBodyPart;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeMultipart;


publicclassMail{

privateMimeMessagemimeMsg;//MIME邮件对象
privateSessionsession;//邮件会话对象
privatePropertiesprops;//系统属性
privatebooleanneedAuth=false;//smtp是否需要认证
//smtp认证用户名和密码
privateStringusername;
privateStringpassword;
privateMultipartmp;//Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象

/**
*Constructor
*@paramsmtp邮件发送服务器
*/
publicMail(Stringsmtp){
setSmtpHost(smtp);
createMimeMessage();
}

/**
*设置邮件发送服务器
*@paramhostNameString
*/
publicvoidsetSmtpHost(StringhostName){
System.out.println("设置系统属性:mail.smtp.host="+hostName);
if(props==null)
props=System.getProperties();//获得系统属性对象
props.put("mail.smtp.host",hostName);//设置SMTP主机
}


/**
*创建MIME邮件对象
*@return
*/
()
{
try{
System.out.println("准备获取邮件会话对象!");
session=Session.getDefaultInstance(props,null);//获得邮件会话对象
}
catch(Exceptione){
System.err.println("获取邮件会话对象时发生错误!"+e);
returnfalse;
}

System.out.println("准备创建MIME邮件对象!");
try{
mimeMsg=newMimeMessage(session);//创建MIME邮件对象
mp=newMimeMultipart();

returntrue;
}catch(Exceptione){
System.err.println("创建MIME邮件对象失败!"+e);
returnfalse;
}
}

/**
*设置SMTP是否需要验证
*@paramneed
*/
publicvoidsetNeedAuth(booleanneed){
System.out.println("设置smtp身份认证:mail.smtp.auth="+need);
if(props==null)props=System.getProperties();
if(need){
props.put("mail.smtp.auth","true");
}else{
props.put("mail.smtp.auth","false");
}
}

/**
*设置用户名和密码
*@paramname
*@parampass
*/
publicvoidsetNamePass(Stringname,Stringpass){
username=name;
password=pass;
}

/**
*设置邮件主题
*@parammailSubject
*@return
*/
publicbooleansetSubject(StringmailSubject){
System.out.println("设置邮件主题!");
try{
mimeMsg.setSubject(mailSubject);
returntrue;
}
catch(Exceptione){
System.err.println("设置邮件主题发生错误!");
returnfalse;
}
}

/**
*设置邮件正文
*@parammailBodyString
*/
publicbooleansetBody(StringmailBody){
try{
BodyPartbp=newMimeBodyPart();
bp.setContent(""+mailBody,"text/html;charset=GBK");
mp.addBodyPart(bp);

returntrue;
}catch(Exceptione){
System.err.println("设置邮件正文时发生错误!"+e);
returnfalse;
}
}
/**
*添加附件
*@paramfilenameString
*/
publicbooleanaddFileAffix(Stringfilename){

System.out.println("增加邮件附件:"+filename);
try{
BodyPartbp=newMimeBodyPart();
FileDataSourcefileds=newFileDataSource(filename);
bp.setDataHandler(newDataHandler(fileds));
bp.setFileName(fileds.getName());

mp.addBodyPart(bp);

returntrue;
}catch(Exceptione){
System.err.println("增加邮件附件:"+filename+"发生错误!"+e);
returnfalse;
}
}

/**
*设置发信人
*@paramfromString
*/
publicbooleansetFrom(Stringfrom){
System.out.println("设置发信人!");
try{
mimeMsg.setFrom(newInternetAddress(from));//设置发信人
returntrue;
}catch(Exceptione){
returnfalse;
}
}
/**
*设置收信人
*@paramtoString
*/
publicbooleansetTo(Stringto){
if(to==null)returnfalse;
try{
mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
returntrue;
}catch(Exceptione){
returnfalse;
}
}

/**
*设置抄送人
*@paramtoString
*/
publicbooleansetCopyTo(Stringto)
{
if(to==null)returnfalse;
try{
mimeMsg.setRecipients(Message.RecipientType.CC,(Address[])InternetAddress.parse(to));
returntrue;
}
catch(Exceptione)
{returnfalse;}
}

/**
*发送邮件
*/
publicbooleansendOut()
{
try{
mimeMsg.setContent(mp);
mimeMsg.saveChanges();
System.out.println("正在发送邮件....");

SessionmailSession=Session.getInstance(props,null);
Transporttransport=mailSession.getTransport("smtp");
transport.connect((String)props.get("mail.smtp.host"),username,password);
transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO));
transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.CC));
//transport.send(mimeMsg);

System.out.println("发送邮件成功!");
transport.close();

returntrue;
}catch(Exceptione){
System.err.println("邮件发送失败!"+e);
returnfalse;
}
}

/**
*调用sendOut方法完成邮件发送
*@paramsmtp
*@paramfrom
*@paramto
*@paramsubject
*@paramcontent
*@paramusername
*@parampassword
*@returnboolean
*/
publicstaticbooleansend(Stringsmtp,Stringfrom,Stringto,Stringsubject,Stringcontent,Stringusername,Stringpassword){
MailtheMail=newMail(smtp);
theMail.setNeedAuth(true);//需要验证

if(!theMail.setSubject(subject))returnfalse;
if(!theMail.setBody(content))returnfalse;
if(!theMail.setTo(to))returnfalse;
if(!theMail.setFrom(from))returnfalse;
theMail.setNamePass(username,password);

if(!theMail.sendOut())returnfalse;
returntrue;
}

/**
*调用sendOut方法完成邮件发送,带抄送
*@paramsmtp
*@paramfrom
*@paramto
*@paramto
*@paramsubject
*@paramcontent
*@paramusername
*@parampassword
*@returnboolean
*/
publicstaticbooleansendAndCc(Stringsmtp,Stringfrom,Stringto,Stringto,Stringsubject,Stringcontent,Stringusername,Stringpassword){
MailtheMail=newMail(smtp);
theMail.setNeedAuth(true);//需要验证

if(!theMail.setSubject(subject))returnfalse;
if(!theMail.setBody(content))returnfalse;
if(!theMail.setTo(to))returnfalse;
if(!theMail.setCopyTo(to))returnfalse;
if(!theMail.setFrom(from))returnfalse;
theMail.setNamePass(username,password);

if(!theMail.sendOut())returnfalse;
returntrue;
}

/**
*调用sendOut方法完成邮件发送,带附件
*@paramsmtp
*@paramfrom
*@paramto
*@paramsubject
*@paramcontent
*@paramusername
*@parampassword
*@paramfilename附件路径
*@return
*/
publicstaticbooleansend(Stringsmtp,Stringfrom,Stringto,Stringsubject,Stringcontent,Stringusername,Stringpassword,Stringfilename){
MailtheMail=newMail(smtp);
theMail.setNeedAuth(true);//需要验证

if(!theMail.setSubject(subject))returnfalse;
if(!theMail.setBody(content))returnfalse;
if(!theMail.addFileAffix(filename))returnfalse;
if(!theMail.setTo(to))returnfalse;
if(!theMail.setFrom(from))returnfalse;
theMail.setNamePass(username,password);

if(!theMail.sendOut())returnfalse;
returntrue;
}

/**
*调用sendOut方法完成邮件发送,带附件和抄送
*@paramsmtp
*@paramfrom
*@paramto
*@paramto
*@paramsubject
*@paramcontent
*@paramusername
*@parampassword
*@paramfilename
*@return
*/
publicstaticbooleansendAndCc(Stringsmtp,Stringfrom,Stringto,Stringto,Stringsubject,Stringcontent,Stringusername,Stringpassword,Stringfilename){
MailtheMail=newMail(smtp);
theMail.setNeedAuth(true);//需要验证

if(!theMail.setSubject(subject))returnfalse;
if(!theMail.setBody(content))returnfalse;
if(!theMail.addFileAffix(filename))returnfalse;
if(!theMail.setTo(to))returnfalse;
if(!theMail.setCopyTo(to))returnfalse;
if(!theMail.setFrom(from))returnfalse;
theMail.setNamePass(username,password);

if(!theMail.sendOut())returnfalse;
returntrue;
}

}

❷ java 代码发邮件怎么添加附件

实现java发送邮件的过程大体有以下几步:

准备一个properties文件,该文件中存放SMTP服务器地址等参数。

利用properties创建一个Session对象

利用Session创建Message对象,然后设置邮件主题和正文

利用Transport对象发送邮件

需要的jar有2个:activation.jar和mail.jar发送附件,需要用到Multipart对象。

importjava.io.File;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.Properties;

importjavax.activation.DataHandler;
importjavax.activation.DataSource;
importjavax.activation.FileDataSource;
importjavax.mail.BodyPart;
importjavax.mail.Message;
importjavax.mail.MessagingException;
importjavax.mail.Multipart;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeBodyPart;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeMultipart;
importjavax.mail.internet.MimeUtility;

{
privateMimeMessagemessage;
privateSessionsession;
privateTransporttransport;

privateStringmailHost="";
privateStringsender_username="";
privateStringsender_password="";

privatePropertiesproperties=newProperties();

/*
*初始化方法
*/
publicJavaMailWithAttachment(booleandebug){
InputStreamin=JavaMailWithAttachment.class.getResourceAsStream("MailServer.properties");
try{
properties.load(in);
this.mailHost=properties.getProperty("mail.smtp.host");
this.sender_username=properties.getProperty("mail.sender.username");
this.sender_password=properties.getProperty("mail.sender.password");
}catch(IOExceptione){
e.printStackTrace();
}

session=Session.getInstance(properties);
session.setDebug(debug);//开启后有调试信息
message=newMimeMessage(session);
}

/**
*发送邮件
*
*@paramsubject
*邮件主题
*@paramsendHtml
*邮件内容
*@paramreceiveUser
*收件人地址
*@paramattachment
*附件
*/
publicvoiddoSendHtmlEmail(Stringsubject,StringsendHtml,StringreceiveUser,Fileattachment){
try{
//发件人
InternetAddressfrom=newInternetAddress(sender_username);
message.setFrom(from);

//收件人
InternetAddressto=newInternetAddress(receiveUser);
message.setRecipient(Message.RecipientType.TO,to);

//邮件主题
message.setSubject(subject);

//向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipartmultipart=newMimeMultipart();

//添加邮件正文
BodyPartcontentPart=newMimeBodyPart();
contentPart.setContent(sendHtml,"text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);

//添加附件的内容
if(attachment!=null){
BodyPartattachmentBodyPart=newMimeBodyPart();
DataSourcesource=newFileDataSource(attachment);
attachmentBodyPart.setDataHandler(newDataHandler(source));

//网上流传的解决文件名乱码的方法,其实用MimeUtility.encodeWord就可以很方便的搞定
//这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
//sun.misc.BASE64Encoderenc=newsun.misc.BASE64Encoder();
//messageBodyPart.setFileName("=?GBK?B?"+enc.encode(attachment.getName().getBytes())+"?=");

//MimeUtility.encodeWord可以避免文件名乱码
attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
multipart.addBodyPart(attachmentBodyPart);
}

//将multipart对象放到message中
message.setContent(multipart);
//保存邮件
message.saveChanges();

transport=session.getTransport("smtp");
//smtp验证,就是你用来发邮件的邮箱用户名密码
transport.connect(mailHost,sender_username,sender_password);
//发送
transport.sendMessage(message,message.getAllRecipients());

System.out.println("sendsuccess!");
}catch(Exceptione){
e.printStackTrace();
}finally{
if(transport!=null){
try{
transport.close();
}catch(MessagingExceptione){
e.printStackTrace();
}
}
}
}

publicstaticvoidmain(String[]args){
JavaMailWithAttachmentse=newJavaMailWithAttachment(true);
Fileaffix=newFile("c:\测试-test.txt");
se.doSendHtmlEmail("邮件主题","邮件内容","[email protected]",affix);//
}
}

❸ 如何使用Java发送qq邮件

方法:

1.前提准备工作:
首先,邮件的发送方要开启POP3 和SMTP服务--即发送qq邮件的账号要开启POP3 和SMTP服务

2.开启方法:
登陆qq邮箱
3.点击 设置

4.点击—-账户

5.找到:POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 —点击开启

6.送短信 —–点击确定

7.稍等一会,很得到一个授权码! –注意:这个一定要记住,一会用到

8.点击保存修改 —OK 完成

9.java 测试代码:
package cn.cupcat.test;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
public class SendmailUtil {
public static void main(String[] args) throws AddressException, MessagingException {

Properties properties = new Properties();
properties.put("mail.transport.protocol", "smtp");// 连接协议
properties.put("mail.smtp.host", "smtp.qq.com");// 主机名
properties.put("mail.smtp.port", 465);// 端口号
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.enable", "true");//设置是否使用ssl安全连接 ---一般都使用
properties.put("mail.debug", "true");//设置是否显示debug信息 true 会在控制台显示相关信息
//得到回话对象
Session session = Session.getInstance(properties);
// 获取邮件对象
Message message = new MimeMessage(session);
//设置发件人邮箱地址
message.setFrom(new InternetAddress("[email protected]"));
//设置收件人地址 message.setRecipients( RecipientType.TO, new InternetAddress[] { new InternetAddress("[email protected]") });
//设置邮件标题
message.setSubject("这是第一封Java邮件");
//设置邮件内容
message.setText("内容为: 这是第一封java发送来的邮件。");
//得到邮差对象
Transport transport = session.getTransport();
//连接自己的邮箱账户
transport.connect("[email protected]", "vvctybgbvvophjcj");//密码为刚才得到的授权码
//发送邮件 transport.sendMessage(message, message.getAllRecipients());
}
}
10.运行就会发出邮件了。。。。
下面是我收到邮件的截图,当然我把源码中的邮件地址都是修改了,不是真实的,你们测试的时候,可以修改能你们自己的邮箱。最后,祝你也能成功,如果有什么问题,可以一起讨论!

注意事项

得到的授权码一定要保存好,程序中要使用

热点内容
apache设置访问ip 发布:2025-09-23 14:41:29 浏览:880
英雄枪战脚本 发布:2025-09-23 14:38:17 浏览:800
c语言报数 发布:2025-09-23 14:36:14 浏览:578
企业邮箱密码在哪里 发布:2025-09-23 14:30:27 浏览:803
编译原理东南大学教材 发布:2025-09-23 14:21:54 浏览:579
现在汽车主流配置是什么 发布:2025-09-23 14:09:45 浏览:742
宿舍感人故事脚本 发布:2025-09-23 14:06:43 浏览:588
阿里云配置外网访问 发布:2025-09-23 14:03:11 浏览:633
当贝播放器ftp教程 发布:2025-09-23 14:02:15 浏览:536
华为p30手机编译器 发布:2025-09-23 13:56:26 浏览:110