java发送邮箱
⑴ 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程序运行结果发送到邮箱
可以选择使用log4j,它是一款开源的日志记录工具,提供发送日志邮件功能
Log4j发送日志邮件的作用: 
      项目错误信息能及时(实时)反映给项目维护人员以及相关负责人。 
优点: 
      1.快速响应; 
      2.共同监督; 
      3.邮件正文直接显示了错误信息,拷贝信息比登陆服务器再查找要方便; 
      4.在日志信息继续写入文件的前提下,多了另外一种获取信息的渠道。 
补充:Log4j可以实现输出到控制台,文件,回滚文件,发送日志邮件,数据库,自定义标签。 
发送邮件的一个重要的类是SMTPAppender,之前用的是 log4j-1.2.8,在1.2.8的版本中,SMTPAppender没有SMTPPassword 和SMTPUsername 属性。这两个属性分别是登录SMTP服务器发送认证的用户名和密码。 
依赖的jar包: 
log4j-1.2.15.jar(版本低于log4j-1.2.14.jar不支持SMTP认证) 
mail.jar 
activation.jar 
在log4j.properties文件中配置: 
### send error through email.
#log4j的邮件发送appender,如果有必要你可以写自己的appender
log4j.appender.MAIL=org.apache.log4j.net.SMTPAppender
#发送邮件的门槛,仅当等于或高于ERROR(比如FATAL)时,邮件才被发送
log4j.appender.MAIL.Threshold=ERROR
#缓存文件大小,日志达到10k时发送Email
log4j.appender.MAIL.BufferSize=10
#发送邮件的邮箱帐号
[email protected]
#SMTP邮件发送服务器地址
log4j.appender.MAIL.SMTPHost=smtp.163.com
#SMTP发送认证的帐号名
[email protected]
#SMTP发送认证帐号的密码
log4j.appender.MAIL.SMTPPassword=xxx
#是否打印调试信息,如果选true,则会输出和SMTP之间的握手等详细信息
log4j.appender.MAIL.SMTPDebug=false
#邮件主题
log4j.appender.MAIL.Subject=Log4JErrorMessage
#发送到什么邮箱,如果要发送给多个邮箱,则用逗号分隔;
#如果需要发副本给某人,则加入下列行
#[email protected]
[email protected]
log4j.appender.MAIL.layout=org.apache.log4j.PatternLayout
log4j.appender.MAIL.layout.ConversionPattern=[framework]%d - %c -%-4r[%t]%-5p %c %x -%m%n
在java代码中,可是用logger.info("message");方法将message代表的消息发送到指定邮箱中
⑶ 怎样用java实现邮件的发送
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;
import java.rmi.UnknownHostException;
import java.util.StringTokenizer;
import sun.misc.BASE64Encoder;
public class Sender {
	//private boolean debug = true;
	BASE64Encoder encode=new BASE64Encoder();//用于加密后发送用户名和密码
	static int dk=25;
private Socket socket;
	public Sender(String server, int port) throws UnknownHostException,
			IOException {
		try {
			socket = new Socket(server, dk);
		} catch (SocketException e) {
			System.out.println(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//System.out.println("已经建立连接!");
		}
	}
	// 注册到邮件服务器
	public void helo(String server, BufferedReader in, BufferedWriter out)
			throws IOException {
		int result;
		result = getResult(in);
		// 连接上邮件服务后,服务器给出220应答
		if (result != 220) {
			throw new IOException("连接服务器失败");
		}
		result = sendServer("HELO " + server, in, out);
		// HELO命令成功后返回250
		if (result != 250) {
			throw new IOException("注册邮件服务器失败!");
		}
	}
	private int sendServer(String str, BufferedReader in, BufferedWriter out)
			throws IOException {
		out.write(str);
		out.newLine();
		out.flush();
		/*
		if (debug) {
			System.out.println("已发送命令:" + str);
		}
		*/
		return getResult(in);
	}
	public int getResult(BufferedReader in) {
		String line = "";
		try {
			line = in.readLine();
			/*
			if (debug) {
				System.out.println("服务器返回状态:" + line);
			}
			*/
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 从服务器返回消息中读出状态码,将其转换成整数返回
		
		StringTokenizer st = new StringTokenizer(line, " ");
		return Integer.parseInt(st.nextToken());
	}
	public void authLogin(MailMessage message, BufferedReader in,
			BufferedWriter out) throws IOException {
		int result;
		result = sendServer("AUTH LOGIN", in, out);
		if (result != 334) {
			throw new IOException("用户验证失败!");
		}
		result=sendServer(encode.encode(message.getUser().getBytes()),in,out);
		//System.out.println("用户名:	"+encode.encode(message.getUser().getBytes()));
		if (result != 334) {
			throw new IOException("用户名错误!");
		}
		result=sendServer(encode.encode(message.getPassword().getBytes()),in,out);
		//result=sendServer(message.getPassword(),in,out);
		//System.out.println("密码:	"+encode.encode(message.getPassword().getBytes()));
		if (result != 235) {
			throw new IOException("验证失败!");
		}
	}
	// 开始发送消息,邮件源地址
	public void mailfrom(String source, BufferedReader in, BufferedWriter out)
			throws IOException {
		int result;
		result = sendServer("MAIL FROM:<" + source + ">", in, out);
		if (result != 250) {
			throw new IOException("指定源地址错误");
		}
	}
	// 设置邮件收件人
	public void rcpt(String touchman, BufferedReader in, BufferedWriter out)
			throws IOException {
		int result;
		result = sendServer("RCPT TO:<" + touchman + ">", in, out);
		if (result != 250) {
			throw new IOException("指定目的地址错误!");
		}
	}
	// 邮件体
	public void data(String from, String to, String subject, String content,
			BufferedReader in, BufferedWriter out) throws IOException {
		int result;
		result = sendServer("DATA", in, out);
		// 输入DATA回车后,若收到354应答后,继续输入邮件内容
		if (result != 354) {
			throw new IOException("不能发送数据");
		}
		out.write("From: " + from);
		out.newLine();
		out.write("To: " + to);
		out.newLine();
		out.write("Subject: " + subject);
		out.newLine();
		out.newLine();
		out.write(content);
		out.newLine();
		// 句号加回车结束邮件内容输入
		result = sendServer(".", in, out);
		//System.out.println(result);
		if (result != 250) {
			throw new IOException("发送数据错误");
		}
	}
	// 退出
	public void quit(BufferedReader in, BufferedWriter out) throws IOException {
		int result;
		result = sendServer("QUIT", in, out);
		if (result != 221) {
			throw new IOException("未能正确退出");
		}
	}
	// 发送邮件主程序
	public boolean sendMail(MailMessage message, String server) {
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
					socket.getOutputStream()));
			helo(server, in, out);// HELO命令
			authLogin(message, in, out);// AUTH LOGIN命令
			mailfrom(message.getFrom(), in, out);// MAIL FROM
			rcpt(message.getTo(), in, out);// RCPT
			data(message.getDatafrom(), message.getDatato(),
					message.getSubject(), message.getContent(), in, out);// DATA
			quit(in, out);// QUIT
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
再写一个MailMessage.java,set/get方法即可。
⑷ 怎么用java调用默认邮件客户端发送邮件
使用Java应用程序发送E-mail十分简单,但是首先你应该在你的机器上安装JavaMail API 和Java Activation Framework (JAF) 。
你可以在 JavaMail (Version 1.2) 下载最新的版本。
你可以再 在JAF (Version 1.1.1)下载最新的版本。
下面是一个发邮件的代码:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
 
public class SendEmail
{
   public static void main(String [] args)
   {   
      // 收件人电子邮箱
      String to = "[email protected]";
 
      // 发件人电子邮箱
      String from = "[email protected]";
 
      // 指定发送邮件的主机为 localhost
      String host = "localhost";
 
      // 获取系统属性
      Properties properties = System.getProperties();
 
      // 设置邮件服务器
      properties.setProperty("mail.smtp.host", host);
 
      // 获取默认session对象
      Session session = Session.getDefaultInstance(properties);
 
      try{
         // 创建默认的 MimeMessage 对象
         MimeMessage message = new MimeMessage(session);
 
         // Set From: 头部头字段
         message.setFrom(new InternetAddress(from));
 
         // Set To: 头部头字段
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));
 
         // Set Subject: 头部头字段
         message.setSubject("This is the Subject Line!");
 
         // 设置消息体
         message.setText("This is actual message");
 
         // 发送消息
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}
⑸ java实现发送邮件功能
要实现邮件发送功能需要导入包:mail.jar
/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package org.demo.action;
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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.demo.form.DemoForm;
public class DemoAction extends Action {
private static final String CONTENT_TYPE = "test/html;charset=GB2312";
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
DemoForm demoForm = (DemoForm) form;
System.out.println("标题是" + demoForm.getBiaoti());
System.out.println("内容是" + demoForm.getNeirong());
try {
response.setContentType(CONTENT_TYPE);
String smtphost = "smtp.nj.headware.cn"; // 发送邮件服务器
String user = "q0000015369"; // 邮件服务器登录用户名
String password = "Queshuwen26"; // 邮件服务器登录密码
String from = "[email protected]"; // 
String to = "[email protected]"; // 收件人邮件地址
String subject = demoForm.getBiaoti(); // 邮件标题
String body = demoForm.getNeirong(); // 邮件内容
Properties props = new Properties();
props.put("mail.smtp.host", smtphost);
props.put("mail.smtp.auth", "true");
Session ssn = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(ssn);
InternetAddress fromAddress = new InternetAddress(from);
message.setFrom(fromAddress);
InternetAddress toAddress = new InternetAddress(to);
message.addRecipient(Message.RecipientType.TO, toAddress);
message.setSubject(subject);
message.setText(body);
Transport transport = ssn.getTransport("smtp");
transport.connect(smtphost, user, password);
transport.sendMessage(message, message
.getRecipients(Message.RecipientType.TO));
// transport.send(message);
transport.close();
return mapping.findForward("succ");
} catch (Exception e) {
e.printStackTrace();
return mapping.findForward("fail");
}
}
}
⑹ Java发邮件的几种方式
下面给你介绍3种发送邮件的方式:
1:使用JavaMail发送邮件

⑺ 怎样用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);
}
}
⑻ java发送邮件(阿里云邮件推送、SendCloud)
详解如下:
https://help.aliyun.com/document_detail/29426.html?spm=5176.proct29412.3.1.7dq3BJ
⑼ 如何使用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实现发邮件功能,并有几点注意事项
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获取资源。
