gpt4 book ai didi

java - 如何从 Java 发送 SMTP 消息?

转载 作者:IT老高 更新时间:2023-10-28 20:26:44 29 4
gpt4 key购买 nike

Possible Duplicate:
How do you send email from a Java app using Gmail?

如何从 Java 发送 SMTP 消息?

最佳答案

以下是 Gmail smtp 的示例:

import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;

import javax.mail.*;

import javax.mail.internet.*;

import com.sun.mail.smtp.*;


public class Distribution {

public static void main(String args[]) throws Exception {
Properties props = System.getProperties();
props.put("mail.smtps.host","smtp.gmail.com");
props.put("mail.smtps.auth","true");
Session session = Session.getInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("mail@tovare.com"));;
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("tov.are.jacobsen@iss.no", false));
msg.setSubject("Heisann "+System.currentTimeMillis());
msg.setText("Med vennlig hilsennTov Are Jacobsen");
msg.setHeader("X-Mailer", "Tov Are's program");
msg.setSentDate(new Date());
SMTPTransport t =
(SMTPTransport)session.getTransport("smtps");
t.connect("smtp.gmail.com", "admin@tovare.com", "<insert password here>");
t.sendMessage(msg, msg.getAllRecipients());
System.out.println("Response: " + t.getLastServerResponse());
t.close();
}
}

现在,仅当您希望将项目依赖项保持在最低限度时才这样做,否则我强烈建议您使用来自 apache 的类

http://commons.apache.org/email/

问候

托夫是雅各布森

关于java - 如何从 Java 发送 SMTP 消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73580/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com