java sendgrid
时间: 2023-10-14 10:32:21 浏览: 106
要使用Java发送邮件,可以使用SendGrid API来发送邮件。下面是一个简单的Java代码示例,说明如何使用SendGrid API:
```java
import com.sendgrid.*;
import java.io.IOException;
public class SendGridExample {
public static void main(String[] args) throws IOException {
Email from = new Email("from_email@example.com");
String subject = "Sending with SendGrid is Fun";
Email to = new Email("to_email@example.com");
Content content = new Content("text/plain", "and easy to do anywhere, even with Java");
Mail mail = new Mail(from, subject, to, content);
SendGrid sg = new SendGrid("SENDGRID_API_KEY");
Request request = new Request();
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
Response response = sg.api(request);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
} catch (IOException ex) {
throw ex;
}
}
}
```
在上面的代码中,我们首先创建了一个`Email`对象表示发送邮件的发件人和收件人的电子邮件地址。然后,我们创建了一个`Mail`对象,将发件人、主题、收件人和内容添加到邮件中。接下来,我们创建一个`SendGrid`对象,并使用API密钥进行身份验证。最后,我们使用`Request`对象将邮件发送到SendGrid服务器。
请注意,您需要将`SENDGRID_API_KEY`替换为您的SendGrid API密钥。
阅读全文