Java编写邮件格式抄收人内容编辑并发送邮件
时间: 2024-03-13 08:47:03 浏览: 24
您可以使用JavaMail API编写Java程序来发送电子邮件。以下是一个简单的示例程序,可以用于设置抄送人并编辑邮件内容:
```java
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 SendEmail {
public static void main(String[] args) {
String to = "recipient@example.com"; // 收件人电子邮件地址
String cc = "cc@example.com"; // 抄送人电子邮件地址
String from = "your_email@example.com"; // 发件人电子邮件地址
String password = "your_email_password"; // 发件人电子邮件密码
// 设置邮件会话属性
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
// 获取邮件会话
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(from, password);
}
});
try {
// 创建电子邮件消息
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setRecipients(Message.RecipientType.CC,
InternetAddress.parse(cc));
message.setSubject("邮件主题");
// 设置邮件消息内容
message.setText("邮件内容");
// 发送电子邮件
Transport.send(message);
System.out.println("电子邮件已发送。");
} catch (AddressException e) {
throw new RuntimeException(e);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
```
在上面的程序中,您需要将`to`,`cc`,`from`和`password`变量替换为您自己的值。您还可以更改邮件会话属性以适应您的邮件服务器配置。