java 用gmail邮件服务器 发送邮件

这篇博客展示了如何使用Java的javamail-api通过Gmail邮件服务器使用TLS安全连接发送电子邮件。示例代码详细解释了设置SMTP参数、创建和发送邮件的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

via TLS
下面代码运行时命令行输入密码会回显,因为实在eclipse下调试,所以System.getConsole.getPassword() 不能用,其他方法又太麻烦,就暂时这样了。另外显示的发送人email地址可以和登录用的gmail地址不一样,但是现在不需要,所以就没加这个功能,需要加

message.setFrom(new InternetAddress("from@no-spam.com"));


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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;

/**
 *
 *
 */
public class GmailUtil {
    
    /**
     * given gmail account (e.g. **@artinfo.com), and password, send an email to the given address
     * @param fromEmailaddress
     * @param password
     * @param toEmailaddress
     * @param body
     * @param subject
     * @return
     */
    public static boolean sendEMail(String fromEmailaddress, String password, String toEmailaddress, String body, String subject) {
        Properties props = System.getProperties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtps.port", Integer.toString(456));
        props.put("mail.smtps.auth", Boolean.toString(true));
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);

        try {

   // 设置不同的发件人        message.setFrom(new InternetAddress("from@no-spam.com"));


            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmailaddress));
            message.setSubject(subject);
            message.setContent(body, "text/html");

            Transport tr = session.getTransport("smtps");
            tr.connect( "smtp.gmail.com", 465, fromEmailaddress, password);
            tr.sendMessage(message, message.getAllRecipients());
            tr.close();
        } catch (AddressException e) {
            e.printStackTrace();
            return false;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    
     public static void main(String[] args) {

            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        
            String userEmail = null;
            String pass = null;
            String toEmail = null;
            String emailBody = null;
            String emailSubject = null;
            
            try {
                    System.out.println("==Please input your gmail address==:");
                userEmail = in.readLine();
                System.out.println("==Please input your gmail password==:");
                pass = in.readLine();
                System.out.println("==Please input email address to send to==:");
                toEmail = in.readLine();
                System.out.println("==Please input your email body==:");
                emailBody = in.readLine();
                System.out.println("==Please input your email subject==:");
                emailSubject = in.readLine();
                    
            } catch (IOException e) {
                e.printStackTrace();
            }


            GmailUtil.sendEMail(userEmail, pass, toEmail, emailBody, emailSubject);
            
            
            
        }

}

下面这个带ssl安全连结,从下面这个地方看到,但是我没测试过:
http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/

Send an Email via Gmail SMTP server using SSL connection.

package com.mkyong.common;
 
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
public class SendMailSSL {
	public static void main(String[] args) {
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");
 
		Session session = Session.getDefaultInstance(props,
			new javax.mail.Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication("username","password");
				}
			});
 
		try {
 
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("from@no-spam.com"));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse("to@no-spam.com"));
			message.setSubject("Testing Subject");
			message.setText("Dear Mail Crawler," +
					"\n\n No spam to my email, please!");
 
			Transport.send(message);
 
			System.out.println("Done");
 
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值