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

java邮件发送

发布时间: 2022-01-08 12:53:27

‘壹’ 怎样用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发邮件的几种方式

下面给你介绍3种发送邮件的方式:

1:使用JavaMail发送邮件

‘叁’ 如何在 java 发邮件中提供链接

这是一个通过Java发送Email的例子,很多新手问道如何用JAVA发邮件,其实挺简单的,Java给我们提供有此方面的类库可以使用,以下就是一个例子:

view source

print?

001
import java.awt.*;

002
import java.awt.event.*;

003
import java.util.*;

004
import java.net.*;

005
import java.io.*;

006
import javax.swing.*;

007
public class MailTest {

008
public static
void main(String[]
args) {

009
JFrame frame = new
MailTestFrame();

010
frame.show();

011
}

012
}

013
class MailTestFrame extends JFrame implements ActionListener {

014
private BufferedReader in;

015
private PrintWriter out;

016
private JTextField from;

017
private JTextField to;

018
private JTextField
smtpServer;

019
private JTextArea message;

020
private JTextArea response;

021

022
public MailTestFrame() {

023
setTitle("MailTest");

024
setSize(300, 300);

025
addWindowListener(new WindowAdapter() {

026
public void windowClosing(WindowEvent e) {

027
System.exit(0);

028
}

029
});

030
getContentPane().setLayout(new GridBagLayout());

031
GridBagConstraints gbc = new GridBagConstraints();

032
// 当容器比组件要大时,只调整垂直方向组件的大小

033
gbc.fill = GridBagConstraints.HORIZONTAL;

034
gbc.weightx = 0;

035
gbc.weighty = 0;

036

037
gbc.weightx = 0;

038
add(new JLabel("发送地址:"), gbc, 0, 0, 1, 1);

039
gbc.weightx = 100;

040
from = new JTextField(20);

041
add(from, gbc, 1, 0, 1, 1);

042
gbc.weightx = 0;

043
add(new JLabel("收件地址:"), gbc, 0, 1, 1, 1);

044
gbc.weightx = 100;

045
to
= new JTextField(20);

046
add(to, gbc, 1, 1, 1, 1);

047
gbc.weightx = 0;

048
add(new JLabel("SMTP服务器:"), gbc,
0, 2, 1, 1);

049
gbc.weightx = 100;

050
smtpServer = new
JTextField(20);

051
add(smtpServer, gbc, 1, 2, 1, 1);

052
gbc.fill = GridBagConstraints.BOTH;

053
gbc.weighty = 100;

054
message = new JTextArea();

055
add(new JScrollPane(message), gbc, 0, 3, 2, 1);

056
response = new JTextArea();

057
add(new JScrollPane(response), gbc, 0, 4, 2, 1);

058
gbc.weighty = 0;

059
JButton sendButton = new JButton("发送");

060
sendButton.addActionListener(this);

061
JPanel buttonPanel = new JPanel();

062
buttonPanel.add(sendButton);

063
add(buttonPanel, gbc, 0, 5, 2, 1);

064
}

065
private void add(Component c, GridBagConstraints gbc, int x, int y, int w,

066
int h) {

067
gbc.gridx = x;

068
gbc.gridy = y;

069
gbc.gridwidth = w;

070
gbc.gridheight = h;

071
getContentPane().add(c, gbc);

072
}

073
public void actionPerformed(ActionEvent evt) {

074
// 异步机制,使得当所有的awt事件发生后才进行以下工作

075
SwingUtilities.invokeLater(new Runnable() {

076
public void run() {

077
sendMail();

078
}

079
});

080
}

081
public void sendMail() {

082
try {

083
Socket s = new Socket(smtpServer.getText(), 25);

084
out = new PrintWriter(s.getOutputStream());

085
in = new BufferedReader(new
InputStreamReader(s.getInputStream()));

086
String hostName = InetAddress.getLocalHost().getHostName();

087
send(null);

088
// 传送本机域名

089
send("HELO " + hostName);

090
// 传送发信者信箱名称

091
send("MAIL FROM: "
+ from.getText());

092
// 传送收信者信箱名称

093
send("RCPT TO: "
+ to.getText());

094
// 发送信箱数据,包括信头和信体

095
send("DATA");

096
out.println(message.getText());

097
// 发送结束标志

098
send(".");

099
s.close();

100
}
catch (IOException exception) {

101
response.append("Error:
" + exception);

102
}

103
}

104
public void send(String s) throws IOException {

105
if (s != null) {

106
response.append(s + "\n");

107
out.println(s);

108
out.flush();

109
}

110
String line;

111
if ((line = in.readLine())
!= null)

112
response.append(line + "\n");

113
}

114
}
转载仅供参考,版权属于原作者。祝你愉快,满意请采纳哦

‘肆’ 如何用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文档。

‘伍’ javaMail如何能保证邮件发送成功

当javamail使用smtp服务发送邮件时,当你把邮件发送到smtp服务器的时候,你只能得到已经发送到smtp的队列中的状态,但是邮件服务器是否能发送成功,你是得不到的。就是说,你不能保证邮件发送一定成功。 这就取决于SMTP协议的内容传输了。

但是SMTP协议如果传输失败,是会报错的。SMTP由TCP提供的可靠的数据传输服务把邮件消息从发信人的邮件服务器传送到收信人的邮件服务器。
所以我们可以认为当我们调用JavaMail发送邮件时,如果程序没有报错则表示邮件发送成功。

SMTP通常有两种工作模式:发送SMTP和接收SMTP。

具体工作方式为:发送SMTP在接到用户的邮件请求后,判断此邮件是否为本地邮件,若是直接投送到用户的邮箱,否则向dns查询远端邮件服务器的 MX纪录,并建立与远端接收SMTP之间的一个双向传送通道,此后SMTP命令由发送SMTP发出,由接收SMTP接收,而应答则反方面传送。一旦传送通 道建立,SMTP发送者发送MAIL命令指明邮件发送者。如果SMTP接收者可以接收邮件则返回OK应答。SMTP发送者再发出RCPT命令确认邮件是否 接收到。如果SMTP接收者接收,则返回OK应答;如果不能接收到,则发出拒绝接收应答(但不中止整个邮件操作),双方将如此重复多次。当接收者收到全部 邮件后会接收到特别的序列,如果接收者成功处理了邮件,则返回OK应答即可。

‘陆’ 怎么用JAVA实现邮件发送

用java mail 库

‘柒’ Java发送邮件

本地要 有smtp服务器,才可以测试 。。。。。。。。。。。。。~
~
~
~~~~~~~~~~~~~~~~~~~~~~~~

‘捌’ 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实现发邮件功能,并有几点注意事项

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获取资源。

热点内容
单片机android 发布:2024-09-20 09:07:24 浏览:765
如何提高三星a7安卓版本 发布:2024-09-20 08:42:35 浏览:664
如何更换服务器网站 发布:2024-09-20 08:42:34 浏览:311
子弹算法 发布:2024-09-20 08:41:55 浏览:289
手机版网易我的世界服务器推荐 发布:2024-09-20 08:41:52 浏览:817
安卓x7怎么边打游戏边看视频 发布:2024-09-20 08:41:52 浏览:162
sql数据库安全 发布:2024-09-20 08:31:32 浏览:94
苹果连接id服务器出错是怎么回事 发布:2024-09-20 08:01:07 浏览:507
编程键是什么 发布:2024-09-20 07:52:47 浏览:658
学考密码重置要求的证件是什么 发布:2024-09-20 07:19:46 浏览:481