新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

通过java代码发邮件 java实现邮件发送功能代码

怎么用java发送邮件,像园子那样

1.首先你需要一个邮箱中转发送站(听着很高端的样子),说白了就是注册一个邮箱作为你的发送邮件平台,然后通过编程调用平台发送邮件(也就是你注册某个邮箱,然后开通SMTP/POP3协议,在编程中,拿着你的KEY去发送邮件),我试过很多种邮箱,QQ貌似不能用,网易经常报错,建议用新浪的,我用基本没出过问题。

目前创新互联已为上千余家的企业提供了网站建设、域名、虚拟空间、网站托管、服务器托管、企业网站设计、石棉网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。

2.去网上下载java开源的发送邮件工具类:mail.jar,并导入myeclipse/eclipse的引用。

3.编程(工具类)

java 怎么实现发送邮件例子

第一个类:MailSenderInfo.java

[java] view plain copy

package com.util.mail;

/**

* 发送邮件需要使用的基本信息

*author by wangfun

小说520

*/

import java.util.Properties;

public class MailSenderInfo {

// 发送邮件的服务器的IP和端口

private String mailServerHost;

private String mailServerPort = "25";

// 邮件发送者的地址

private String fromAddress;

// 邮件接收者的地址

private String toAddress;

// 登陆邮件发送服务器的用户名和密码

private String userName;

private String password;

// 是否需要身份验证

private boolean validate = false;

// 邮件主题

private String subject;

// 邮件的文本内容

private String content;

// 邮件附件的文件名

private String[] attachFileNames;

/**

* 获得邮件会话属性

*/

public Properties getProperties(){

Properties p = new Properties();

p.put("mail.smtp.host", this.mailServerHost);

p.put("mail.smtp.port", this.mailServerPort);

p.put("mail.smtp.auth", validate ? "true" : "false");

return p;

}

public String getMailServerHost() {

return mailServerHost;

}

public void setMailServerHost(String mailServerHost) {

this.mailServerHost = mailServerHost;

}

public String getMailServerPort() {

return mailServerPort;

}

public void setMailServerPort(String mailServerPort) {

this.mailServerPort = mailServerPort;

}

public boolean isValidate() {

return validate;

}

public void setValidate(boolean validate) {

this.validate = validate;

}

public String[] getAttachFileNames() {

return attachFileNames;

}

public void setAttachFileNames(String[] fileNames) {

this.attachFileNames = fileNames;

}

public String getFromAddress() {

return fromAddress;

}

public void setFromAddress(String fromAddress) {

this.fromAddress = fromAddress;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public String getToAddress() {

return toAddress;

}

public void setToAddress(String toAddress) {

this.toAddress = toAddress;

}

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

public String getSubject() {

return subject;

}

public void setSubject(String subject) {

this.subject = subject;

}

public String getContent() {

return content;

}

public void setContent(String textContent) {

this.content = textContent;

}

}

第二个类:SimpleMailSender.java

[java] view plain copy

package com.util.mail;

import java.util.Date;

import java.util.Properties;

import javax.mail.Address;

import javax.mail.BodyPart;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Multipart;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

/**

* 简单邮件(不带附件的邮件)发送器

BT下载

*/

public class SimpleMailSender {

/**

* 以文本格式发送邮件

* @param mailInfo 待发送的邮件的信息

*/

public boolean sendTextMail(MailSenderInfo mailInfo) {

// 判断是否需要身份认证

MyAuthenticator authenticator = null;

Properties pro = mailInfo.getProperties();

if (mailInfo.isValidate()) {

// 如果需要身份认证,则创建一个密码验证器

authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());

}

// 根据邮件会话属性和密码验证器构造一个发送邮件的session

Session sendMailSession = Session.getDefaultInstance(pro,authenticator);

try {

// 根据session创建一个邮件消息

Message mailMessage = new MimeMessage(sendMailSession);

// 创建邮件发送者地址

Address from = new InternetAddress(mailInfo.getFromAddress());

// 设置邮件消息的发送者

mailMessage.setFrom(from);

// 创建邮件的接收者地址,并设置到邮件消息中

Address to = new InternetAddress(mailInfo.getToAddress());

mailMessage.setRecipient(Message.RecipientType.TO,to);

// 设置邮件消息的主题

mailMessage.setSubject(mailInfo.getSubject());

// 设置邮件消息发送的时间

mailMessage.setSentDate(new Date());

// 设置邮件消息的主要内容

String mailContent = mailInfo.getContent();

mailMessage.setText(mailContent);

// 发送邮件

Transport.send(mailMessage);

return true;

} catch (MessagingException ex) {

ex.printStackTrace();

}

return false;

}

/**

* 以HTML格式发送邮件

* @param mailInfo 待发送的邮件信息

*/

public static boolean sendHtmlMail(MailSenderInfo mailInfo){

// 判断是否需要身份认证

MyAuthenticator authenticator = null;

Properties pro = mailInfo.getProperties();

//如果需要身份认证,则创建一个密码验证器

if (mailInfo.isValidate()) {

authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());

}

// 根据邮件会话属性和密码验证器构造一个发送邮件的session

Session sendMailSession = Session.getDefaultInstance(pro,authenticator);

try {

// 根据session创建一个邮件消息

Message mailMessage = new MimeMessage(sendMailSession);

// 创建邮件发送者地址

Address from = new InternetAddress(mailInfo.getFromAddress());

// 设置邮件消息的发送者

mailMessage.setFrom(from);

// 创建邮件的接收者地址,并设置到邮件消息中

Address to = new InternetAddress(mailInfo.getToAddress());

// Message.RecipientType.TO属性表示接收者的类型为TO

mailMessage.setRecipient(Message.RecipientType.TO,to);

// 设置邮件消息的主题

mailMessage.setSubject(mailInfo.getSubject());

// 设置邮件消息发送的时间

mailMessage.setSentDate(new Date());

// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象

Multipart mainPart = new MimeMultipart();

// 创建一个包含HTML内容的MimeBodyPart

BodyPart html = new MimeBodyPart();

// 设置HTML内容

html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");

mainPart.addBodyPart(html);

// 将MiniMultipart对象设置为邮件内容

mailMessage.setContent(mainPart);

// 发送邮件

Transport.send(mailMessage);

return true;

} catch (MessagingException ex) {

ex.printStackTrace();

}

return false;

}

}

第三个类:MyAuthenticator.java

[java] view plain copy

package com.util.mail;

import javax.mail.*;

public class MyAuthenticator extends Authenticator{

String userName=null;

String password=null;

public MyAuthenticator(){

}

public MyAuthenticator(String username, String password) {

this.userName = username;

this.password = password;

}

protected PasswordAuthentication getPasswordAuthentication(){

return new PasswordAuthentication(userName, password);

}

}

下面给出使用上面三个类的代码:

[java] view plain copy

public static void main(String[] args){

//这个类主要是设置邮件

MailSenderInfo mailInfo = new MailSenderInfo();

mailInfo.setMailServerHost("smtp.163.com");

mailInfo.setMailServerPort("25");

mailInfo.setValidate(true);

mailInfo.setUserName("han2000lei@163.com");

mailInfo.setPassword("**********");//您的邮箱密码

mailInfo.setFromAddress("han2000lei@163.com");

mailInfo.setToAddress("han2000lei@163.com");

mailInfo.setSubject("设置邮箱标题 如 中国桂花网");

mailInfo.setContent("设置邮箱内容 如 中国桂花网 是中国最大桂花网站==");

//这个类主要来发送邮件

SimpleMailSender sms = new SimpleMailSender();

sms.sendTextMail(mailInfo);//发送文体格式

sms.sendHtmlMail(mailInfo);//发送html格式

}

最后,给出朋友们几个注意的地方:

1、使用此代码你可以完成你的javamail的邮件发送功能。三个类缺一不可。

2、这三个类我打包是用的com.util.mail包,如果不喜欢,你可以自己改,但三个类文件必须在同一个包中

3、不要使用你刚刚注册过的邮箱在程序中发邮件,如果你的163邮箱是刚注册不久,那你就不要使用“smtp.163.com”。因为你发不出去。刚注册的邮箱是不会给你这种权限的,也就是你不能通过验证。要使用你经常用的邮箱,而且时间比较长的。

4、另一个问题就是mailInfo.setMailServerHost("smtp.163.com");与mailInfo.setFromAddress("han2000lei@163.com");这两句话。即如果你使用163smtp服务器,那么发送邮件地址就必须用163的邮箱,如果不的话,是不会发送成功的。

5、关于javamail验证错误的问题,网上的解释有很多,但我看见的只有一个。就是我的第三个类。你只要复制全了代码,我想是不会有问题的。

怎样用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发送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("123456789@qq.com"));

//设置收件人地址 message.setRecipients( RecipientType.TO, new InternetAddress[] { new InternetAddress("987654321@qq.com") });

//设置邮件标题

message.setSubject("这是第一封Java邮件");

//设置邮件内容

message.setText("内容为: 这是第一封java发送来的邮件。");

//得到邮差对象

Transport transport = session.getTransport();

//连接自己的邮箱账户

transport.connect("123456789@qq.com", "vvctybgbvvophjcj");//密码为刚才得到的授权码

//发送邮件 transport.sendMessage(message, message.getAllRecipients());

}

}

10.运行就会发出邮件了。。。。

下面是我收到邮件的截图,当然我把源码中的邮件地址都是修改了,不是真实的,你们测试的时候,可以修改能你们自己的邮箱。最后,祝你也能成功,如果有什么问题,可以一起讨论!

注意事项

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


本文名称:通过java代码发邮件 java实现邮件发送功能代码
网页链接:http://www.wjwzjz.com/article/hhocsh.html
在线咨询
服务热线
服务热线:028-86922220
TOP