① java 发送邮件,内容是要从数据库中读取的数据并列成表格的状态发送出去
publicbooleansendTextMail(MailSenderInfomailInfo){
//判断是否需要身份认证
MyAuthenticatorauthenticator=null;
Propertiespro=mailInfo.getProperties();
if(mailInfo.isValidate()){
//如果需要身份认证,则创建一个密码验证器
authenticator=newMyAuthenticator(mailInfo.getUserName(),mailInfo.getPassword());
}
//根据邮件会话属性和密码验证器构造一个发送邮件的session
SessionsendMailSession=null;
//sendMailSession=Session.getDefaultInstance(pro,authenticator);//获取默认可能报错
sendMailSession=Session.getInstance(pro,authenticator);//新创建一个session
if(sendMailSession==null){
System.out.println("无法获取邮件邮件Session");
}
try{
//根据session创建一个邮件消息
MessagemailMessage=newMimeMessage(sendMailSession);
//创建邮件发送者地址
Addressfrom=newInternetAddress(mailInfo.getFromAddress());
//设置邮件消息的发送者
mailMessage.setFrom(from);
//创建邮件的接收者地址,并设置到邮件消息中
Addressto=newInternetAddress(mailInfo.getToAddress());
mailMessage.setRecipient(Message.RecipientType.TO,to);
//设置邮件消息的主题
mailMessage.setSubject(mailInfo.getSubject());
//设置邮件消息发送的时间
mailMessage.setSentDate(newDate());
//设置邮件消息的主要内容
StringmailContent=mailInfo.getContent();
mailMessage.setText(mailContent);//添加附件
//if(mailInfo.getAttachFileNames()!=null||mailInfo.getAttachFileNames().length>0){
//Multipartmp=newMimeMultipart();
//MimeBodyPartmbp=null;
//for(StringfileName:mailInfo.getAttachFileNames()){
//mbp=newMimeBodyPart();
//FileDataSourcefds=newFileDataSource(fileName);//得到数据源
//mbp.setDataHandler(newDataHandler(fds));//得到附件本身并至入BodyPart
//mbp.setFileName(fds.getName());//得到文件名同样至入BodyPart
//mp.addBodyPart(mbp);
//}
//mailMessage.setContent(mp);
//}
//发送邮件
Transport.send(mailMessage);
returntrue;
}catch(MessagingExceptionex){
ex.printStackTrace();
}
returnfalse;
}
publicclassMailSenderInfo{
//发送邮件的服务器的IP和端口
privateStringmailServerHost;
privateStringmailServerPort="25";
//邮件发送者的地址
privateStringfromAddress;
//邮件接收者的地址
privateStringtoAddress;
//登陆邮件发送服务器的用户名和密码
privateStringuserName;
privateStringpassword;
//是否需要身份验证
privatebooleanvalidate=false;
//邮件主题
privateStringsubject;
//邮件的文本内容
privateStringcontent;
//邮件附件的文件名
privateString[]attachFileNames;
//邮件抄送人
privateList<String>ccUserList;
/***//**
*获得邮件会话属性
*/
publicPropertiesgetProperties(){
Propertiesp=newProperties();
p.put("mail.smtp.host",this.mailServerHost);
p.put("mail.smtp.port",this.mailServerPort);
p.put("mail.smtp.auth",validate?"true":"false");
returnp;
}
publicStringgetMailServerHost(){
returnmailServerHost;
}
publicvoidsetMailServerHost(StringmailServerHost){
this.mailServerHost=mailServerHost;
}
publicStringgetMailServerPort(){
returnmailServerPort;
}
publicvoidsetMailServerPort(StringmailServerPort){
this.mailServerPort=mailServerPort;
}
publicbooleanisValidate(){
returnvalidate;
}
publicvoidsetValidate(booleanvalidate){
this.validate=validate;
}
publicString[]getAttachFileNames(){
returnattachFileNames;
}
publicvoidsetAttachFileNames(String[]fileNames){
this.attachFileNames=fileNames;
}
publicStringgetFromAddress(){
returnfromAddress;
}
publicvoidsetFromAddress(StringfromAddress){
this.fromAddress=fromAddress;
}
publicStringgetPassword(){
returnpassword;
}
publicvoidsetPassword(Stringpassword){
this.password=password;
}
publicStringgetToAddress(){
returntoAddress;
}
publicvoidsetToAddress(StringtoAddress){
this.toAddress=toAddress;
}
publicStringgetUserName(){
returnuserName;
}
publicvoidsetUserName(StringuserName){
this.userName=userName;
}
publicStringgetSubject(){
returnsubject;
}
publicvoidsetSubject(Stringsubject){
this.subject=subject;
}
publicStringgetContent(){
returncontent;
}
publicvoidsetContent(StringtextContent){
this.content=textContent;
}
publicList<String>getCcUserList(){
returnccUserList;
}
publicvoidsetCcUserList(List<String>ccUserList){
this.ccUserList=ccUserList;
}
}
publicstaticvoidmain(String[]args){
//这个类主要是设置邮件
MailSenderInfomailInfo=newMailSenderInfo();
mailInfo.setMailServerHost("smtp.163.com");
mailInfo.setMailServerPort("25");
mailInfo.setValidate(true);
mailInfo.setUserName("[email protected]");
mailInfo.setPassword("zzzong0828");//您的邮箱密码
mailInfo.setFromAddress("");
//接受方信息
mailInfo.setToAddress("");
mailInfo.setSubject("邮箱标题");
mailInfo.setContent("设置邮箱内容如http://www.guihua.org中国桂花网是中国最大桂花网站==");
String[]files=newString[]{"D:/1.txt","D:/2.txt","D:/3.txt"};
mailInfo.setAttachFileNames(files);
//这个类主要来发送邮件
SimpleMailSendersms=newSimpleMailSender();
sms.sendTextMail(mailInfo);//发送文体格式
//sms.sendHtmlMail(mailInfo);//发送html格式
}
这样发
② javamail发送带Excel附件邮件
我这里有个可用的。也来自网络,测了下可以。。
③ 如何用java实现发邮件功能,并有几点注意事项
packagecom.victor;
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);
System.out.println(se);
Fileaffix=newFile("E:\测试-test.txt");
//Fileaffix=null;
se.doSendHtmlEmail("##","###","####@##.com",affix);//
}
}
注意点:1 jar可能有冲突,如果是demo可以直接应用mail.jar
如果是一个工程则要替换javaEE中的mail.jar包
2 关于properties配置文件的地址问题
Class.getResourceAsStream(String path) : path 不以’/'开头时默认是从此类所在的包下取资源,以’/'开头则是从
ClassPath根下获取。其只是通过path构造一个绝对路径,最终还是由ClassLoader获取资源。
④ 如何用java实现邮件发送
javamail
没错 就是这个 你看看api就能写出来 顺便说下 ,javamail群发的时候 要注意 发送的时候开个线程,等几秒再发下一个 要不会被邮件服务器拒绝的
⑤ java调取excel表格内容,再调用javamail api直接发送
http://www.cnblogs.com/xwdreamer/archive/2012/02/22/2363152.html poi读取excel
http://www.blogjava.net/wangfun/archive/2009/04/15/265748.html 发送你的邮件
⑥ 如何使用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.运行就会发出邮件了。。。。
下面是我收到邮件的截图,当然我把源码中的邮件地址都是修改了,不是真实的,你们测试的时候,可以修改能你们自己的邮箱。最后,祝你也能成功,如果有什么问题,可以一起讨论!
注意事项
得到的授权码一定要保存好,程序中要使用
⑦ 如何用java实现发送html格式的邮件
首先Java发送邮件需要用到JavaMail,先到Oracle官网上下载好最新版本的JavaMail(刚才看了一下,最新是1.5.3),把下载的这个jar文件放到classpath里(如果是Web项目,就放到WEB-INF/lib目录下。
JavaMail主要支持发送纯文本的和html格式的邮件。
发送html格式的邮件的一个例程如下:
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeUtility;
importjavax.mail.Session;
importjavax.mail.MessagingException;
importjavax.mail.Transport;
publicclassSendHtmlMail{
publicstaticvoidsendMessage(StringsmtpHost,
Stringfrom,Stringto,
Stringsubject,StringmessageText)
throwsMessagingException,java.io.UnsupportedEncodingException{
//Step1:Configurethemailsession
System.out.println("Configuringmailsessionfor:"+smtpHost);
java.util.Propertiesprops=newjava.util.Properties();
props.setProperty("mail.smtp.auth","true");//指定是否需要SMTP验证
props.setProperty("mail.smtp.host",smtpHost);//指定SMTP服务器
props.put("mail.transport.protocol","smtp");
SessionmailSession=Session.getDefaultInstance(props);
mailSession.setDebug(true);//是否在控制台显示debug信息
//Step2:Constructthemessage
System.out.println("Constructingmessage-from="+from+"to="+to);
InternetAddressfromAddress=newInternetAddress(from);
InternetAddresstoAddress=newInternetAddress(to);
MimeMessagetestMessage=newMimeMessage(mailSession);
testMessage.setFrom(fromAddress);
testMessage.addRecipient(javax.mail.Message.RecipientType.TO,toAddress);
testMessage.setSentDate(newjava.util.Date());
testMessage.setSubject(MimeUtility.encodeText(subject,"gb2312","B"));
testMessage.setContent(messageText,"text/html;charset=gb2312");
System.out.println("Messageconstructed");
//Step3:Nowsendthemessage
Transporttransport=mailSession.getTransport("smtp");
transport.connect(smtpHost,"webmaster","password");
transport.sendMessage(testMessage,testMessage.getAllRecipients());
transport.close();
System.out.println("Messagesent!");
}
publicstaticvoidmain(String[]args){
StringsmtpHost="localhost";
Stringfrom="[email protected]";
Stringto="[email protected]";
Stringsubject="html邮件测试";//subjectjavamail自动转码
StringBuffertheMessage=newStringBuffer();
theMessage.append("<h2><fontcolor=red>这倒霉孩子</font></h2>");
theMessage.append("<hr>");
theMessage.append("<i>年年失望年年望</i>");
try{
SendHtmlMail.sendMessage(smtpHost,from,to,subject,theMessage.toString());
}
catch(javax.mail.MessagingExceptionexc){
exc.printStackTrace();
}
catch(java.io.){
exc.printStackTrace();
}
}
}
JavaMail是封装了很多邮件操作的,所以使用起来不很困难,建议你到JavaMail官网看一下API或下载Java Doc API文档。
⑧ java 发送邮件
要两个java文件 还有一个mail.jar是不是只能用javamail谁也不敢说
第一个:
public class Constant {
public static final String mailAddress ="用户名@163.com";
public static final String mailCount ="用户名";
public static final String mailPassword ="密码";
public static final String mailServer ="smtp.163.com";
//pukeyouxintest,
}
第二个:
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
/**
* 发送简单邮件
* @param str_from:发件人地址
* @param str_to:收件人地址
* @param str_title:邮件标题
* @param str_content:邮件正文
*/
public static void send(String str_from,String str_to,String str_title,String str_content) {
// str_content="<a href='www.163.com'>html元素</a>"; //for testing send html mail!
try {
//建立邮件会话
Properties props=new Properties(); //用来在一个文件中存储键-值对的,其中键和值是用等号分隔的,
//存储发送邮件服务器的信息
props.put("mail.smtp.host",Constant.mailServer);
//同时通过验证
props.put("mail.smtp.auth","true");
//根据属性新建一个邮件会话
Session s=Session.getInstance(props);
s.setDebug(true); //有他会打印一些调试信息。
//由邮件会话新建一个消息对象
MimeMessage message=new MimeMessage(s);
//设置邮件
InternetAddress from= new InternetAddress(str_from); //[email protected]
message.setFrom(from); //设置发件人的地址
//
// //设置收件人,并设置其接收类型为TO
InternetAddress to=new InternetAddress(str_to); //[email protected]
message.setRecipient(Message.RecipientType.TO, to);
//设置标题
message.setSubject(str_title); //java学习
//设置信件内容
// message.setText(str_content); //发送文本邮件 //你好吗?
message.setContent(str_content, "text/html;charset=gbk"); //发送HTML邮件 //<b>你好</b><br><p>大家好</p>
//设置发信时间
message.setSentDate(new Date());
//存储邮件信息
message.saveChanges();
//发送邮件
Transport transport=s.getTransport("smtp");
//以smtp方式登录邮箱,第一个参数是发送邮件用的邮件服务器SMTP地址,第二个参数为用户名,第三个参数为密码
transport.connect(Constant.mailServer,Constant.mailCount,Constant.mailPassword);
//发送邮件,其中第二个参数是所有已设好的收件人地址
transport.sendMessage(message,message.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//测试用的,你吧你想写的内容写上去就行
send(Constant.mailAddress,"收件人邮箱","标题","<b>内容</b>");
}
}
然后把mail.jar导入,就可以了,我用的是163 的,其他的吧相应的服务器改一下就行了
⑨ 怎样用java发送邮件
首先下载 JavaMail jar 包,并导入到项目中。下载地址
编写代码,代码如下:
importjavax.mail.Authenticator;
importjavax.mail.Message;
importjavax.mail.MessagingException;
importjavax.mail.PasswordAuthentication;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.AddressException;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeMessage;
publicclassApp45{
publicstaticvoidmain(String[]args)throwsAddressException,MessagingException{
Propertiesproperties=System.getProperties();
properties.setProperty("mail.smtp.host","邮件发送服务器");
properties.setProperty("mail.smtp.auth","true");
Sessionsession=Session.getDefaultInstance(properties,newAuthenticator(){
@Override
(){
//设置发件人邮件帐号和密码
("邮件帐号","密码");
}
});
MimeMessagemessage=newMimeMessage(session);
//设置发件人邮件地址
message.setFrom(newInternetAddress("发件人邮件地址"));
//设置收件人邮件地址
message.addRecipient(Message.RecipientType.TO,newInternetAddress("收件人邮件地址"));
message.setSubject("这里是邮件主题。");
message.setText("这里是邮件内容。");
Transport.send(message);
}
}