0 votes
by (240 points)

Buongiorno,
c'è qualche proprietà per ricavare da MailMessage.From l'indirizzo mail del mittente pulito?
Ad esempio sulle mail ricevute da PEC vedo scritto: "Ricevuto per conto di:" indirizzomail server pec.
A me servirebbe estrarre solo l'indirizzo mail.
Grazie.
Simone Zanetti.

Applies to: Rebex Secure Mail

2 Answers

0 votes
by (240 points)

Ho risolto da solo utilizzando questo codice:

    Dim i As Integer
    Dim mail As New MailMessage
    mail.Load(NomeMailAttiva)
    Dim From As String = mail.From.ToString
    Dim indirizzi As Rebex.Mime.Headers.MailAddressCollection
    indirizzi = mail.From
    Dim indirizzo As Rebex.Mime.Headers.MailAddress
    For i = 0 To indirizzi.Count - 1
        indirizzo = indirizzi.Item(0)
        MessageBox.Show(indirizzo.Address)
    Next

Non è particolarmente bello da vedere ma funziona.
Grazie.

0 votes
by (70.2k points)

Please note that MailMessage.From property is a MailAddressCollection object, which is collection of MailAddress objects. The MailAddress.Address property is what you probably want to read.

Example:

var mail = new MailMessage();
mail.From = "\"Received on behalf of: Foo Bar\" <foo@example.com>";

// print the FROM header
Console.WriteLine(mail.From);

// print SMTP address of the first entry in the FROM header
Console.WriteLine(mail.From[0].Address);
by (240 points)
Grazie per la celere risposta.
In realtà non funziona ancora del tutto come vorrei.
Se ad esempio l'attributo "from" contiene questa stringa: "Per conto di: bccroma@ciscrapec.it" <posta-certificata@pec.aruba.it> la proprietà "Address" mi restituisce "posta-certificata@pec.aruba.it" e invece dovrebbe restituirmi "bccroma@ciscrapec.it".
E' possibile ricavarlo?
Cordiali saluti.
by (70.2k points)
What does contain MailMessage.Sender property?

Maybe, the address you want is specified in the SENDER header.
If not, you have to parse the address from the mail.From property yourself.

In case of "Per conto di: bccroma@ciscrapec.it" this whole string is considered to be a Display Name for the SMTP address "posta-certificata@pec.aruba.it"

There is no build-in method for your task, but something like this should do the trick:

    Dim address As String
    If mail.From.Count = 0 OrElse
        String.IsNullOrEmpty(mail.From(0).DisplayName) OrElse
        Not mail.From(0).DisplayName.Contains(":"c) _
    Then
        address = String.Empty
    Else
        address = mail.From(0).DisplayName.Split(":"c)(1).Trim()
    End If
...