Ответ 1
Вы можете установить имя в InternetAddress
, используя
new InternetAddress("[email protected]", "Your Name");
Я пытаюсь отправить почту своим друзьям через приложение Java Mail. Я могу сделать это успешно, однако столбец получателя в почтовом ящике показывает полный адрес электронной почты, а не имя отправителя. Я попытался изменить различные параметры, но почтовый ящик покажет полный адрес электронной почты, а не имя отправителя.
используя этот метод для отправки сообщения:
public void send(String key){
String to=key;
String from="mygmailid";
String subject="wassp";
String text="Hello";
Properties props=new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.user", "myname");
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 mailSession=Session.getDefaultInstance(props);
Message simpleMessage=new MimeMessage(mailSession);
InternetAddress fromAddress=null;
InternetAddress toAddress=null;
try{
fromAddress=new InternetAddress(from);
toAddress=new InternetAddress(to);
}
catch(AddressException e){
e.printStackTrace();
}
try{
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO,toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
transport.connect("smtp.gmail.com",465, "[email protected]", "mygmailpassword");
transport.sendMessage(simpleMessage, simpleMessage.getAllRecipients());
transport.close();
}
catch(MessagingException e){
e.printStackTrace();
}
}
Я вызываю этот метод как:
public static void main(String[] args) {
MailSender mailer=new MailSender();
mailer.send("[email protected]");
}
Вы можете установить имя в InternetAddress
, используя
new InternetAddress("[email protected]", "Your Name");
Вы должны использовать двухструнный конструктор InternetAddress для передачи как по адресу электронной почты, так и по имени человека. Получающееся электронное письмо будет содержать строку, обозначенную Jarrod.
InternetAddress fromAddress=new InternetAddress("[email protected]", "John Doe");
Как отображается поле from - это конкретная деталь реализации клиента.
Обычно, если отправитель находится в форме "Sender Name" <[email protected]>
, клиент будет делать правильную вещь в зависимости от конфигурации.
Некоторые клиенты будут вызывать информацию о названии из своей адресной книги, если она отсутствует.
try {
String from = " EMAIL ID";
String SMTP_AUTH_PWD = " PASSWORD ";
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.auth", "true");
String SMTP_HOST_NAME = "smtp.gmail.com";
int SMTP_HOST_PORT = 465;
javax.mail.Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);
Transport transport = ((javax.mail.Session) mailSession)
.getTransport();
javax.mail.Message message = new MimeMessage(mailSession);
message.setSubject("Testing SMTP-SSL");
message.setContent("", "text/plain");
message.addRecipient(javax.mail.Message.RecipientType.TO,
new InternetAddress(receiver));
transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, from,
SMTP_AUTH_PWD);
message.setFrom(new InternetAddress(from," YOUR PREFERED NAME "));
message.setSubject(subject);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(body);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
message.setContent(multipart);
transport.sendMessage(message,
message.getRecipients(javax.mail.Message.RecipientType.TO));
}
Ответы, приведенные выше, верны, но я обнаружил, что мне нужно поместить в try catch для его работы, вот что я нашел, работая из демонстрационного приложения sendemailwebapp.
Сообщение msg = new MimeMessage (сеанс);
try {
msg.setFrom(new InternetAddress(userName, "YourName"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);
Попробуйте этот код в блоке try. Вы можете инициализировать свое имя в методе setFrom() MimeMessage.
simpleMessage.setFrom(new InternetAddress("Your mail id", "Your name"));
т
try{
simpleMessage.setFrom(new InternetAddress("Your mail id", "Your name"));
simpleMessage.setRecipient(RecipientType.TO,toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
transport.connect("smtp.gmail.com",465, "[email protected]", "mygmailpassword");
transport.sendMessage(simpleMessage, simpleMessage.getAllRecipients());
transport.close();
}