1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Java中使用SMTP协议发送电子邮件

Java中使用SMTP协议发送电子邮件

时间:2023-03-28 17:28:40

相关推荐

Java中使用SMTP协议发送电子邮件

Java中使用SMTP协议发送电子邮件的具体的步骤:

1、首先需要获取发送邮件的Session对象

Session session = Session.getDefaultInstance(properties,authorcator);

2、根据session对象,获取待发送的邮件消息

MimeMessage mimeMessage = new MimeMessage(session);

3、设置发件人,收件人,标题,邮件内容,附件,发送时间等;

4、利用Transport发送邮件

5、代码必须依赖与mail.jar 包

Java实现代码:

1、发送邮件,注意:该类有两个功能,一个是发送普通文本邮件;一个是发送html邮件,两者的本质是相同的,mime类型有所区别而已:

/*** 使用SMTP协议发送电子邮件*/public class SendMail{// 邮件发送协议private final static String PROTOCOL = "smtp";// SMTP邮件服务器private final static String HOST = "smtp.";// SMTP邮件服务器默认端口private final static String PORT = "25";// 是否要求身份认证private final static String IS_AUTH = "true";// 是否启用调试模式(启用调试模式可打印客户端与服务器交互过程时一问一答的响应消息)private final static String IS_ENABLED_DEBUG_MOD = "true";// 发件人private static String from = "test_adimin@";// 初始化连接邮件服务器的会话信息private static Properties props = null;static {props = new Properties();props.setProperty("mail.transport.protocol", PROTOCOL);props.setProperty("mail.smtp.host", HOST);props.setProperty("mail.smtp.port", PORT);props.setProperty("mail.smtp.auth", IS_AUTH);props.setProperty("mail.debug", IS_ENABLED_DEBUG_MOD);}/*** 发送电子邮件* @param address 邮件地址* @param fileNames 文件名* @param files 文件* @param title 文件主题* @param content 文件内容* @throws Exception*/public static void sendHtmlEmail(Address[] address, String[] fileNames,File[] files, String title, String content) throws Exception {// 创建Session实例对象Session session = Session.getDefaultInstance(props,new MyAuthenticator());// 创建邮件内容MimeMessage message = new MimeMessage(session);// 邮件主题,并指定编码格式message.setSubject(title, "utf-8");// 发件人message.setFrom(new InternetAddress(from));// 收件人message.setRecipients(RecipientType.BCC, address);// 创建一个MIME子类型为“related”的MimeMultipart对象MimeMultipart mp = new MimeMultipart("mixed");// 创建一个表示正文的MimeBodyPart对象,并将它加入到前面创建的MimeMultipart对象中MimeBodyPart htmlPart = new MimeBodyPart();mp.addBodyPart(htmlPart);// 将MimeMultipart对象设置为整个邮件的内容message.setContent(mp);try {MimeBodyPart[] mbp = new MimeBodyPart[fileNames.length];DataSource ds1;DataHandler dh1;for (int i = 0; i < fileNames.length; i++) {mbp[i] = new MimeBodyPart();mp.addBodyPart(mbp[i]);ds1 = new FileDataSource(files[i + 1]);dh1 = new DataHandler(ds1);mbp[i].setFileName(MimeUtility.encodeText(fileNames[i]));mbp[i].setDataHandler(dh1);}} catch (Exception e) {e.printStackTrace();}// 创建一个MIME子类型为"alternative"的MimeMultipart对象,并作为前面创建的htmlPart对象的邮件内容MimeMultipart htmlMultipart = new MimeMultipart("alternative");// 创建一个表示html正文的MimeBodyPart对象MimeBodyPart htmlBodypart = new MimeBodyPart();// 其中cid=androidlogo.gif是引用邮件内部的图片,即imagePart.setContentID("androidlogo.gif");方法所保存的图片htmlBodypart.setContent("<span'>" + content + "</span>","text/html;charset=utf-8");htmlMultipart.addBodyPart(htmlBodypart);htmlPart.setContent(htmlMultipart);// 保存并生成最终的邮件内容message.saveChanges();// 发送邮件Transport.send(message);}static class MyAuthenticator extends Authenticator {private String username = "test_adimin@";private String password = "1";public MyAuthenticator() {super();}public MyAuthenticator(String username, String password) {super();this.username = username;this.password = password;}@Overrideprotected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(username, password);}}public static void main(String[] args) throws Exception {sendHtmlEmail(new Address[]{new InternetAddress("869095990@", "", "utf-8")},new String[]{"da","da"},new File[]{},"aa","aa");}}

2、创建身份验证:

/** Licensed to the Apache Software Foundation (ASF) under one* or more contributor license agreements. See the NOTICE file* distributed with this work for additional information* regarding copyright ownership. The ASF licenses this file* to you under the Apache License, Version 2.0 (the* "License"); you may not use this file except in compliance* with the License. You may obtain a copy of the License at** /licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing,* software distributed under the License is distributed on an* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY* KIND, either express or implied. See the License for the* specific language governing permissions and limitations* under the License.*/package javax.mail;import .InetAddress;/*** @version $Rev: 467553 $ $Date: -10-25 00:01:51 -0400 (Wed, 25 Oct ) $*/public abstract class Authenticator {private InetAddress host;private int port;private String prompt;private String protocol;private String username;synchronized PasswordAuthentication authenticate(InetAddress host, int port, String protocol, String prompt, String username) {this.host = host;this.port = port;this.protocol = protocol;this.prompt = prompt;this.username = username;return getPasswordAuthentication();}protected final String getDefaultUserName() {return username;}protected PasswordAuthentication getPasswordAuthentication() {return null;}protected final int getRequestingPort() {return port;}protected final String getRequestingPrompt() {return prompt;}protected final String getRequestingProtocol() {return protocol;}protected final InetAddress getRequestingSite() {return host;}}

另一种比较详细的详细的写法参照这个博客,写的很详细/blog/303

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。