「邮件功能java」邮件功能尚未启用

博主:adminadmin 2022-12-02 12:18:07 75

今天给各位分享邮件功能java的知识,其中也会对邮件功能尚未启用进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

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 = "q0000015369@nj.headware.cn"; //

String to = "c0000016205@nj.headware.cn"; // 收件人邮件地址

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发送邮件

2:发送文本邮件

3:发送 HTML 格式的邮件

Java收发邮件过程中具体的功能是怎么实现的

1.SMTP协议

用户连上邮件服务器后,要想给它发送一封电子邮件,需要遵循一定的通迅规则,SMTP协议就是用于定义这种通讯规则的。

因而,通常我们也把处理用户smtp请求(邮件发送请求)的邮件服务器称之为SMTP服务器。(25)

2.POP3协议

同样,用户若想从邮件服务器管理的电子邮箱中接收一封电子邮件的话,他连上邮件服务器后,也需要遵循一定的通迅格式,POP3协议用于定义这种通讯格式。

因而,通常我们也把处理用户pop3请求(邮件接收请求)的邮件服务器称之为POP3服务器。(110)

下图用于演示两帐户相互发送邮件的过程

3.1JavaMail API按其功能划分通常可分为如下三大类:

创建和解析邮件内容的API :Message类是创建和解析邮件的核心API,它的实例对象代表一封电子邮件。

3.2发送邮件的API:Transport类是发送邮件的核心API类,它的实例对象代表实现了某个邮件发送协议的邮件发送对象,例如SMTP协议。

接收邮件的API:Store类是接收邮件的核心API类,它的实例对象代表实现了某个邮件接收协议的邮件接收对象,例如POP3协议。

3.3Session类

Session类用于定义整个应用程序所需的环境信息,以及收集客户端与邮件服务器建立网络连接的会话信息,如邮件服务器的主机名、端口号、采用的邮件发送和接收协议等。Session对象根据这些信息构建用于邮件收发的Transport和Store对象,以及为客户端创建Message对象时提供信息支持。

4.邮件组织结构相关的API

MimeMessage类表示整封邮件。

MimeBodyPart类表示邮件的一个MIME消息。

MimeMultipart类表示一个由多个MIME消息组合成的组合MIME消息。

5.具体的例子程序

package cn.edu.dlmu.send;

import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.FileDataSource;

import javax.mail.Message;

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;

import javax.mail.internet.MimeUtility;

public class SendMail {

public static void main(String[] args) throws Exception {

Properties prop = new Properties();

//连接的邮件服务器的主机名

prop.setProperty("mail.smtp.host", "smtp.sina.com.cn");

//发送邮件的协议

prop.setProperty("mail.transport.protocol", "smtp");

//是否向邮件服务器提交认证

prop.setProperty("mail.smtp.auth", "true");

//创建session

Session session = Session.getInstance(prop);

session.setDebug(true);

//得到transport

Transport ts = session.getTransport();

//连接邮件服务器

ts.connect("smtp.sina.com.cn", "xxxx@sina.com", "xxxxx");

//发送邮件

MimeMessage message = createMessage(session);

ts.sendMessage(message, message.getAllRecipients());

ts.close();

}

public static MimeMessage createMessage(Session session) throws Exception {

MimeMessage message = new MimeMessage(session);

//设置邮件的基本信息

message.setFrom(new InternetAddress("xxxx@sina.com"));

message.setRecipient(Message.RecipientType.TO, new InternetAddress("1219070362@qq.com"));

message.setSubject("test");

//正文

MimeBodyPart text = new MimeBodyPart();

//设置charaset可以解决中文正文的乱码问题,内嵌可下载的图片

text.setContent("你好xxx,img src='c:/dog.jpg' /测试成功!br/img src='cid:aaa.jpg' /", "text/html;charset=gbk");

//图片1

MimeBodyPart image = new MimeBodyPart();

image.setDataHandler(new DataHandler(new FileDataSource("src/88.jpg")));

image.setContentID("aaa.jpg");

//附件

MimeBodyPart attach = new MimeBodyPart();

DataHandler dh = new DataHandler(new FileDataSource("src/javamail架包.jar"));

attach.setDataHandler(dh);

//解决文件中文乱码问题

attach.setFileName(MimeUtility.encodeText(dh.getName()));

//描述正文和图片的关系

MimeMultipart mp = new MimeMultipart();

mp.addBodyPart(text);

mp.addBodyPart(image);

mp.setSubType("related");

//描述正文和附件

MimeMultipart mp2 = new MimeMultipart();

mp2.addBodyPart(attach);

//将正文封装为一个body

MimeBodyPart content = new MimeBodyPart();

content.setContent(mp);

mp2.addBodyPart(content);

mp2.setSubType("mixed");

message.setContent(mp2);

message.saveChanges();

return message;

}

}

怎么用JAVA实现邮件发送

一个小例子,也可使用其他api

import java.util.Properties;

import javax.mail.Address;

import javax.mail.Authenticator;

import javax.mail.BodyPart;

import javax.mail.Message;

import javax.mail.Multipart;

import javax.mail.PasswordAuthentication;

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;

import javax.mail.internet.MimeUtility;

public class Test {

// test

public static void main(String[] args) throws Exception {

sendEmail("smtp.163.com", "测试", "测试", "!!!收件人地址!!!", "!!!发件人邮箱用户名!!!", "!!!邮箱密码!!!", "发件人昵称");

}

/**

 * 

 * @param smtp

 * @throws Exception 

 */

public static void sendEmail(String emailServer, String subject, String mailBody, String receiver, final String username, final String password, String nickname) throws Exception {

Properties props = new Properties();

props.put("mail.smtp.auth", "true");

props.setProperty("mail.transport.protocol", "smtp");

props.setProperty("mail.smtp.host", emailServer);

props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

props.setProperty("mail.smtp.socketFactory.fallback", "false");

props.setProperty("mail.smtp.port", "465");

props.setProperty("mail.smtp.socketFactory.port", "465");

Session session = Session.getDefaultInstance(props, new Authenticator() {

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(username, password);

}

});

session.setDebug(true);

MimeMessage mimeMsg = new MimeMessage(session);

Multipart mp = new MimeMultipart();

mimeMsg.setSubject(MimeUtility.encodeText(subject, "utf-8", null));

nickname = MimeUtility.encodeText(nickname, "utf-8", null);

mimeMsg.setFrom(new InternetAddress(username, nickname, "UTF-8"));

BodyPart bp = new MimeBodyPart();

bp.setContent(mailBody, "text/html;charset=utf-8");

mp.addBodyPart(bp);

mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));

mimeMsg.setContent(mp);

mimeMsg.saveChanges();

Transport transport = session.getTransport();

transport.connect(username, password);

Address[] allRecipients = mimeMsg.getAllRecipients();

transport.sendMessage(mimeMsg, allRecipients);

transport.close();

}

}

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

package com.victor;

import java.io.File;

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

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;

import javax.mail.internet.MimeUtility;

public class JavaMailWithAttachment {

    private MimeMessage message;

    private Session session;

    private Transport transport;

    private String mailHost = "";

    private String sender_username = "";

    private String sender_password = "";

    private Properties properties = new Properties();

    /*

     * 初始化方法

     */

    public JavaMailWithAttachment(boolean debug) {

        InputStream in = 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 (IOException e) {

            e.printStackTrace();

        }

        

        session = Session.getInstance(properties);

        session.setDebug(debug);//开启后有调试信息

        message = new MimeMessage(session);

    }

    /**

     * 发送邮件

     * 

     * @param subject

     *            邮件主题

     * @param sendHtml

     *            邮件内容

     * @param receiveUser

     *            收件人地址

     * @param attachment

     *            附件

     */

    public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) {

        try {

            // 发件人

            InternetAddress from = new InternetAddress(sender_username);

            message.setFrom(from);

            // 收件人

            InternetAddress to = new InternetAddress(receiveUser);

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

            // 邮件主题

            message.setSubject(subject);

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

            Multipart multipart = new MimeMultipart();

            

            // 添加邮件正文

            BodyPart contentPart = new MimeBodyPart();

            contentPart.setContent(sendHtml, "text/html;charset=UTF-8");

            multipart.addBodyPart(contentPart);

            

            // 添加附件的内容

            if (attachment != null) {

                BodyPart attachmentBodyPart = new MimeBodyPart();

                DataSource source = new FileDataSource(attachment);

                attachmentBodyPart.setDataHandler(new DataHandler(source));

                

                // 网上流传的解决文件名乱码的方法,其实用MimeUtility.encodeWord就可以很方便的搞定

                // 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码

                //sun.misc.BASE64Encoder enc = new sun.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("send success!");

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            if (transport != null) {

                try {

                    transport.close();

                } catch (MessagingException e) {

                    e.printStackTrace();

                }

            }

        }

    }

    public static void main(String[] args) {

        JavaMailWithAttachment se = new JavaMailWithAttachment(true);

        System.out.println(se);

        File affix = new File("E:\\测试-test.txt");

      //  File affix =null;

        se.doSendHtmlEmail("##", "###", "####@##.com", affix);//

    }

}

注意点:1 jar可能有冲突,如果是demo可以直接应用mail.jar

如果是一个工程则要替换javaEE中的mail.jar包

2 关于properties配置文件的地址问题

Class.getResourceAsStream(String path) : path 不以’/'开头时默认是从此类所在的包下取资源,以’/'开头则是从

ClassPath根下获取。其只是通过path构造一个绝对路径,最终还是由ClassLoader获取资源。

邮件功能java的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于邮件功能尚未启用、邮件功能java的信息别忘了在本站进行查找喔。

The End

发布于:2022-12-02,除非注明,否则均为首码项目网原创文章,转载请注明出处。